当前位置: 首页>>代码示例>>Golang>>正文


Golang reflect.Select函数代码示例

本文整理汇总了Golang中reflect.Select函数的典型用法代码示例。如果您正苦于以下问题:Golang Select函数的具体用法?Golang Select怎么用?Golang Select使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Select函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Select

func (self *Selector) Select() (interface{}, error) {
	nCases := len(self.cases)
sel:
	i := 1
	for i < nCases && self.buffers[i-1] == nil {
		i++
	}
	if i == nCases { // no buffered value
		n, v, ok := reflect.Select(self.cases[1:i]) // no default case
		if !ok {
			return nil, ChanClosedErr{Chan: self.cases[n+1].Chan}
		}
		self.buffers[n] = &box{v.Interface()}
		goto sel
	} else { // has buffered value
		n, v, ok := reflect.Select(self.cases[:i]) // default case at index 0
		if !ok && n > 0 {
			return nil, ChanClosedErr{Chan: self.cases[n].Chan}
		}
		if n > 0 { // higher priority chan received
			self.buffers[n-1] = &box{v.Interface()}
			goto sel
		}
		// default
		for i, buf := range self.buffers {
			if buf != nil {
				self.buffers[i] = nil
				return buf.v, nil
			}
		}
	}
	panic("impossible")
	return nil, nil
}
开发者ID:reusee,项目名称:priorityselect,代码行数:34,代码来源:priorityselect.go

示例2: pullSubtask

func (d *Dispatcher) pullSubtask(accepts []string) (*dispatcher.Subtask, error) {
	tc := time.After(PullTimeout)
	cases := make([]reflect.SelectCase, len(accepts)+1)
	var timeoutIdx = len(accepts)
	for i, v := range accepts {
		q := d.ensureQueue(v)
		cases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(q)}
	}
	cases[timeoutIdx] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(tc)}

	for {
		chosen, value, _ := reflect.Select(cases)
		if chosen == timeoutIdx {
			return nil, ErrTimeout
		}

		subtask := value.Interface().(*dispatcher.Subtask)
		d.mu.RLock()
		_, ok := d.result[subtask.ID]
		d.mu.RUnlock()
		if ok {
			return subtask, nil
		}
	}
}
开发者ID:applepi-icpc,项目名称:icarus,代码行数:25,代码来源:dispatcher.go

示例3: Start

func (r *Runner) Start() {
	err := r.handler.Perform()

	if err != nil {
		log.Print(err)
	}

	event_cases := make([]reflect.SelectCase, len(r.watchers))

	for i, watcher := range r.watchers {
		localEventChan := make(chan *etcd.Response)
		event_cases[i] = reflect.SelectCase{
			Dir:  reflect.SelectRecv,
			Chan: reflect.ValueOf(localEventChan),
		}

		go watcher.Start(localEventChan)
	}

	for {
		_, _, ok := reflect.Select(event_cases)
		log.Printf("Received a new event")
		if !ok {
			log.Printf("Spotted a chan close, returning")
			return
		}
		err := r.handler.Perform()

		if err != nil {
			log.Print(err)
		}
	}
}
开发者ID:lucmichalski,项目名称:etcdexpose,代码行数:33,代码来源:runner.go

示例4: Start

func (r *Runner) Start() {
	consumerChan := make(chan bool, r.bufferSize)
	r.handler.Run(consumerChan)

	// Init the consumer
	consumerChan <- true

	eventCases := make([]reflect.SelectCase, len(r.watchers))

	for i, watcher := range r.watchers {
		eventCases[i] = reflect.SelectCase{
			Dir: reflect.SelectRecv,
			Chan: reflect.ValueOf(
				watcher.Start(),
			),
		}

	}

	for {
		chosen, _, ok := reflect.Select(eventCases)
		log.Printf("Received a new event")
		if !ok {
			log.Printf(
				"Spotted a chan close at %d, returning\n",
				chosen,
			)
			close(consumerChan)
			return
		}
		consumerChan <- true
	}
}
开发者ID:upfluence,项目名称:etcdexpose,代码行数:33,代码来源:runner.go

示例5: Select

func (s *Selector) Select() {
	for i := 0; i < len(s.cases); i++ {
		if s.predict[i] != nil {
			if !s.predict[i]() {
				s.selecting[i] = emptyCase
			} else {
				s.selecting[i] = s.cases[i]
			}
		}
		if s.toSend[i] != nil {
			ret := s.toSend[i].Call(nil)
			s.selecting[i].Send = ret[0]
		}
	}
	n, recv, ok := reflect.Select(s.selecting)
	if s.selecting[n].Dir == reflect.SelectRecv {
		if ok {
			if s.cbs[n] != nil {
				switch cb := s.cbs[n].(type) {
				case func():
					cb()
				default:
					reflect.ValueOf(cb).Call([]reflect.Value{
						recv,
					})
				}
			}
		}
	} else {
		if s.cbs[n] != nil {
			(s.cbs[n].(func()))()
		}
	}
}
开发者ID:reusee,项目名称:conditional-select,代码行数:34,代码来源:select.go

示例6: channelIntoSlice

// channelIntoSlice buffers channel data into a slice.
func channelIntoSlice(w http.ResponseWriter, r *http.Request, from interface{}) interface{} {
	ctx := r.Context()

	var to []interface{}
	for {
		switch chosen, recv, ok := reflect.Select([]reflect.SelectCase{
			{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ctx.Done())},
			{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(from)},
		}); chosen {
		case 0: // equivalent to: case <-ctx.Done()
			http.Error(w, "Server Timeout", 504)
			return nil

		default: // equivalent to: case v, ok := <-stream
			if !ok {
				return to
			}
			v := recv.Interface()

			// Present each channel item.
			if presenter, ok := r.Context().Value(presenterCtxKey).(Presenter); ok {
				r, v = presenter.Present(r, v)
			}

			to = append(to, v)
		}
	}
}
开发者ID:pressly,项目名称:chi,代码行数:29,代码来源:render.go

示例7: collect

func (n *N) collect(ch Chans) <-chan []EventInfo {
	done := make(chan []EventInfo)
	go func() {
		cases := make([]reflect.SelectCase, len(ch))
		unique := make(map[<-chan EventInfo]EventInfo, len(ch))
		for i := range ch {
			cases[i].Chan = reflect.ValueOf(ch[i])
			cases[i].Dir = reflect.SelectRecv
		}
		for i := len(cases); i != 0; i = len(cases) {
			j, v, ok := reflect.Select(cases)
			if !ok {
				n.t.Fatal("unexpected chan close")
			}
			ch := cases[j].Chan.Interface().(chan EventInfo)
			got := v.Interface().(EventInfo)
			if ei, ok := unique[ch]; ok {
				n.t.Fatalf("duplicated event %v (previous=%v) received on collect", got, ei)
			}
			unique[ch] = got
			cases[j], cases = cases[i-1], cases[:i-1]
		}
		collected := make([]EventInfo, 0, len(ch))
		for _, ch := range unique {
			collected = append(collected, ch)
		}
		done <- collected
	}()
	return done
}
开发者ID:kaocs,项目名称:notify,代码行数:30,代码来源:testing_test.go

示例8: Drain

func (c Chans) Drain() (ei []EventInfo) {
	n := len(c)
	stop := make(chan struct{})
	eich := make(chan EventInfo, n*buffer)
	go func() {
		defer close(eich)
		cases := make([]reflect.SelectCase, n+1)
		for i := range c {
			cases[i].Chan = reflect.ValueOf(c[i])
			cases[i].Dir = reflect.SelectRecv
		}
		cases[n].Chan = reflect.ValueOf(stop)
		cases[n].Dir = reflect.SelectRecv
		for {
			i, v, ok := reflect.Select(cases)
			if i == n {
				return
			}
			if !ok {
				panic("(Chans).Drain(): unexpected chan close")
			}
			eich <- v.Interface().(EventInfo)
		}
	}()
	<-time.After(50 * time.Duration(n) * time.Millisecond)
	close(stop)
	for e := range eich {
		ei = append(ei, e)
	}
	return
}
开发者ID:kaocs,项目名称:notify,代码行数:31,代码来源:testing_test.go

示例9: receive

func receive(inputs []chan int) <-chan *Output {
	//START OMIT
	cases := make([]reflect.SelectCase, len(inputs))
	output := make(chan *Output)

	for i, input := range inputs {
		cases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(input)}
	}

	go func() {
		defer close(output)
		for {
			index, recv, ok := reflect.Select(cases)
			if !ok {
				cases[index] = cases[len(cases)-1]
				cases = cases[0 : len(cases)-1]

				if len(cases) == 0 {
					break
				}
				continue
			}

			output <- &Output{Index: index, Payload: int(recv.Int())}
		}
	}()
	//END OMIT

	return output
}
开发者ID:GoSteelProgrammers,项目名称:go_the_path_to_1_1,代码行数:30,代码来源:post-select.go

示例10: arbitraryFanIn

// fix was to add a go func to write to out. I don't love this solution becuase it makes order
// of stuff coming out of the out channel non-deterministic, so any other ideas are invited.
func arbitraryFanIn(newChannels <-chan chan interface{}, out chan<- interface{}, removeOnEvent bool) {
	go func() {
		var ch <-chan interface{}
		chans := make([]reflect.SelectCase, 0)
		timeout := time.Tick(10 * time.Millisecond)
		chans = append(chans, reflect.SelectCase{
			Dir:  reflect.SelectRecv,
			Chan: reflect.ValueOf(timeout),
		})
		for {
			select {
			case ch = <-newChannels:
				chans = append(chans, reflect.SelectCase{
					Dir:  reflect.SelectRecv,
					Chan: reflect.ValueOf(ch),
				})
			default:
				chosen, value, ok := reflect.Select(chans)
				if chosen == 0 {
					continue
				}
				if removeOnEvent || !ok {
					lastIndex := len(chans) - 1
					chans[chosen] = chans[lastIndex]
					chans = chans[:lastIndex]
				}
				if ok {
					go func() { out <- value.Interface() }()
				}
			}
		}
	}()
}
开发者ID:vichetuc,项目名称:gobox,代码行数:35,代码来源:client.go

示例11: WaitForNetworkConnectivity

// WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
// periodically check for network connectivity. It returns true if
// no NetworkConnectivityChecker is provided (waiting is disabled)
// or when NetworkConnectivityChecker.HasNetworkConnectivity()
// indicates connectivity. It waits and polls the checker once a second.
// If any stop is broadcast, false is returned immediately.
func WaitForNetworkConnectivity(
	connectivityChecker NetworkConnectivityChecker, stopBroadcasts ...<-chan struct{}) bool {
	if connectivityChecker == nil || 1 == connectivityChecker.HasNetworkConnectivity() {
		return true
	}
	NoticeInfo("waiting for network connectivity")
	ticker := time.NewTicker(1 * time.Second)
	for {
		if 1 == connectivityChecker.HasNetworkConnectivity() {
			return true
		}

		selectCases := make([]reflect.SelectCase, 1+len(stopBroadcasts))
		selectCases[0] = reflect.SelectCase{
			Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ticker.C)}
		for i, stopBroadcast := range stopBroadcasts {
			selectCases[i+1] = reflect.SelectCase{
				Dir: reflect.SelectRecv, Chan: reflect.ValueOf(stopBroadcast)}
		}

		chosen, _, ok := reflect.Select(selectCases)
		if chosen == 0 && ok {
			// Ticker case, so check again
		} else {
			// Stop case
			return false
		}
	}
}
开发者ID:fxckgfw,项目名称:psiphon-tunnel-core,代码行数:35,代码来源:net.go

示例12: Start

func (self *evPipe) Start() {

	// 开始后, 不能修改数组
	self.arrayLock = true

	go func() {

		cases := make([]reflect.SelectCase, len(self.qarray))

		// 按照队列(peer)数量开始做case
		for i, q := range self.qarray {
			cases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(q.queue)}
		}

		for {

			if index, value, ok := reflect.Select(cases); ok {

				self.qarray[index].CallData(value.Interface())
			}

		}

	}()

}
开发者ID:CaiGuaiNi,项目名称:cellnet,代码行数:26,代码来源:pipe.go

示例13: Match

func (matcher *BeClosedMatcher) Match(actual interface{}) (success bool, err error) {
	if !isChan(actual) {
		return false, fmt.Errorf("BeClosed matcher expects a channel.  Got:\n%s", format.Object(actual, 1))
	}

	channelType := reflect.TypeOf(actual)
	channelValue := reflect.ValueOf(actual)

	if channelType.ChanDir() == reflect.SendDir {
		return false, fmt.Errorf("BeClosed matcher cannot determine if a send-only channel is closed or open.  Got:\n%s", format.Object(actual, 1))
	}

	winnerIndex, _, open := reflect.Select([]reflect.SelectCase{
		reflect.SelectCase{Dir: reflect.SelectRecv, Chan: channelValue},
		reflect.SelectCase{Dir: reflect.SelectDefault},
	})

	var closed bool
	if winnerIndex == 0 {
		closed = !open
	} else if winnerIndex == 1 {
		closed = false
	}

	return closed, nil
}
开发者ID:cross-dev,项目名称:script-server,代码行数:26,代码来源:be_closed_matcher.go

示例14: waitForSignal

func (g *orderedGroup) waitForSignal(signals <-chan os.Signal, errTrace ErrorTrace) (os.Signal, ErrorTrace) {
	cases := make([]reflect.SelectCase, 0, len(g.pool)+1)
	for i := 0; i < len(g.pool); i++ {
		cases = append(cases, reflect.SelectCase{
			Dir:  reflect.SelectRecv,
			Chan: reflect.ValueOf(g.pool[g.members[i].Name].Wait()),
		})
	}
	cases = append(cases, reflect.SelectCase{
		Dir:  reflect.SelectRecv,
		Chan: reflect.ValueOf(signals),
	})

	chosen, recv, _ := reflect.Select(cases)
	if chosen == len(cases)-1 {
		return recv.Interface().(os.Signal), errTrace
	}

	var err error
	if !recv.IsNil() {
		err = recv.Interface().(error)
	}

	errTrace = append(errTrace, ExitEvent{
		Member: g.members[chosen],
		Err:    err,
	})

	return g.terminationSignal, errTrace
}
开发者ID:qinguoan,项目名称:vulcan,代码行数:30,代码来源:ordered.go

示例15: loop

func loop(rc reflect.Value, wc reflect.Value) {
	readCase := reflect.SelectCase{}
	readCase.Dir = reflect.SelectRecv
	readCase.Chan = wc

	writeCase := reflect.SelectCase{}
	writeCase.Dir = reflect.SelectSend
	writeCase.Chan = rc

	cases := []reflect.SelectCase{readCase, writeCase}

	l := list.New()

	for {
		tc := cases[:1]
		if l.Len() > 0 {
			writeCase.Send = reflect.ValueOf(l.Front().Value)
			cases[1] = writeCase
			tc = cases[:2]
		}

		idx, v, ok := reflect.Select(tc)
		if idx == 0 {
			if ok {
				l.PushBack(v.Interface())
			} else {
				//channel closed
				log.Println("Read channel closed")
				break
			}
		} else if idx == 1 {
			l.Remove(l.Front())
		}
	}
}
开发者ID:vuleetu,项目名称:misc,代码行数:35,代码来源:channel.go


注:本文中的reflect.Select函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。