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


Golang sync.Cond类代码示例

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


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

示例1: TestNoRaceCond

func TestNoRaceCond(t *testing.T) { // tsan's test02
	ch := make(chan bool, 1)
	var x int = 0
	var mu sync.Mutex
	var cond *sync.Cond = sync.NewCond(&mu)
	var condition int = 0
	var waker func()
	waker = func() {
		x = 1
		mu.Lock()
		condition = 1
		cond.Signal()
		mu.Unlock()
	}

	var waiter func()
	waiter = func() {
		go waker()
		cond.L.Lock()
		for condition != 1 {
			cond.Wait()
		}
		cond.L.Unlock()
		x = 2
		ch <- true
	}
	go waiter()
	<-ch
}
开发者ID:timnau,项目名称:golang,代码行数:29,代码来源:sync_test.go

示例2: printLoop

func printLoop(ch <-chan []grid2d.Update, g grid2d.Grid, cns *census.DirCensus, cond *sync.Cond, numUpdates *int64, clearScreen bool) {
	// Try to keep rendering smooth.
	runtime.LockOSThread()

	for _ = range ch {
		if clearScreen {
			// TODO(dnesting): use termcap/terminfo to do this more portably.
			fmt.Print("[H")
		}
		term.PrintWorld(os.Stdout, g)
		fmt.Println()
		if clearScreen {
			fmt.Print("[J")
		}

		// Write some summary stats after the rendering.
		fmt.Printf("%d updates\n", atomic.LoadInt64(numUpdates))
		fmt.Printf("%d/%d orgs (%d/%d species, %d recorded)\n", cns.Count(), cns.CountAllTime(), cns.Distinct(), cns.DistinctAllTime(), cns.NumRecorded())
		if loc := g.Get(0, 0); loc != nil {
			fmt.Printf("random: %v\n", loc.Value())
		}

		// If we're running with --sync, signal to any goroutines waiting on a rendering that
		// it's OK for them to continue again.
		if cond != nil {
			cond.Broadcast()
		}
	}
}
开发者ID:dnesting,项目名称:alife,代码行数:29,代码来源:main.go

示例3: GetCommandFunc

// Returns a function that will return any commands, or
// nil when no other commands are defined. It will also signal the passed
// Condition when if are no commands left and the Condition is not nil.
func GetCommandFunc(c *types.Connection, startWait *sync.Cond, moreCommands CommandFunc) CommandFunc {
	commands := make(chan string, 5) // command1-5
	//if c.Options.PostCommands { // official PCM ignores this flag... yay.
	for _, v := range []string{
		c.Commands.Command1, c.Commands.Command2, c.Commands.Command3,
		c.Commands.Command4, c.Commands.Command5} {
		if strings.TrimSpace(v) != "" {
			commands <- v
		}
	}
	//}
	return func() *string {
		select {
		case v := <-commands:
			return &v
		default:
			if c := moreCommands(); c != nil {
				return c
			} else if startWait != nil {
				startWait.Broadcast()
			}
			return nil
		}
	}
}
开发者ID:cfstras,项目名称:pcm,代码行数:28,代码来源:commands.go

示例4: SleepUntil

func (t *RealTimer) SleepUntil(cond *sync.Cond, timestamp time.Time) {
	now := t.Now()
	delay := timestamp.Sub(now)
	if delay > 0 {
		tt := time.AfterFunc(time.Duration(delay), func() { cond.Broadcast() })
		t.Sleep(cond)
		tt.Stop()
	}
}
开发者ID:pgm,项目名称:gospoke,代码行数:9,代码来源:timeline.go

示例5: main

func main() {
	var mtx sync.Mutex
	var cnd *sync.Cond
	var cnds [N]*sync.Cond
	var mtxs [N]sync.Mutex
	cnd = sync.NewCond(&mtx)
	for i := 0; i < N; i++ {
		cnds[i] = sync.NewCond(&mtxs[i])
	}
	for i := 0; i < N; i++ {
		go func(me int, m *sync.Mutex, c1 *sync.Cond, c2 *sync.Cond) {
			fmt.Printf("Hello, world. %d\n", me)
			if me == 0 {
				cnd.Signal()
			}
			for j := 0; j < 10000000; j++ {
				m.Lock()
				c1.Wait()
				m.Unlock()
				c2.Signal()
			}
			if me == N-1 {
				cnd.Signal()
			}
		}(i, &mtxs[i], cnds[i], cnds[(i+1)%N])
	}
	mtx.Lock()
	cnd.Wait()
	mtx.Unlock()
	cnds[0].Signal()
	mtx.Lock()
	cnd.Wait()
	mtx.Unlock()
}
开发者ID:benjaminy,项目名称:Charcoal,代码行数:34,代码来源:bucket_brigade.go

示例6: newCondDeadline

func newCondDeadline(cond *sync.Cond) (ret *condDeadline) {
	ret = &condDeadline{
		timer: time.AfterFunc(math.MaxInt64, func() {
			mu.Lock()
			ret._exceeded = true
			mu.Unlock()
			cond.Broadcast()
		}),
	}
	ret.setDeadline(time.Time{})
	return
}
开发者ID:skycoin,项目名称:skycoin,代码行数:12,代码来源:inproc.go

示例7: Schedule

// Schedule configures the timer to call c.Broadcast() when the timer expires.
// It returns true if the caller should defer a call to t.Stop().
func (t *timer) Schedule(c *sync.Cond) bool {
	if t.now != 0 {
		if t.Timer == nil {
			t.Timer = time.AfterFunc(time.Duration(t.rem), func() {
				// c.L must be held to guarantee that the caller is waiting
				c.L.Lock()
				defer c.L.Unlock()
				c.Broadcast()
			})
			return true
		}
		t.Reset(time.Duration(t.rem))
	}
	return false
}
开发者ID:jappre,项目名称:mutation,代码行数:17,代码来源:net.go

示例8: monitorChannel

func monitorChannel(channelID string, api *slack.Client, messageChan <-chan *slack.MessageEvent, msgQueue *utility.Queue, monitorSize, doLogging bool, histCond *sync.Cond, threadWait *sync.WaitGroup) {
	defer threadWait.Done()
	defer logging.Log.Noticef("(%s) Finished monitoring channel", channelID)

	logging.Log.Infof("(%s) Waiting for history", channelID)
	histCond.L.Lock()
	histCond.Wait()
	histCond.L.Unlock()

	logging.Log.Debugf("(%s) Message queue has %v items", channelID, msgQueue.Len())

	logging.Log.Infof("(%s) Monitor size: %v", channelID, monitorSize)
	logging.Log.Infof("(%s) Do logging: %v", channelID, doLogging)

	logging.Log.Infof("(%s) Waiting for events", channelID)
monitorLoop:
	for {
		select {
		case message, chanOpen := <-messageChan:
			if !chanOpen {
				logging.Log.Errorf("(%s) Incoming message channel is closed", channelID)
				break monitorLoop
			}
			/*
				logging.Log.Debugf("(%s) Received message", channelID)
				logging.Log.Debugf("\tUser: %s", message.User)
				logging.Log.Debugf("\tChannel: %s", message.Channel)
				logging.Log.Debugf("\tTimestamp: %s", message.Timestamp)
				logging.Log.Debugf("\tText: %s", message.Text)
				logging.Log.Debugf("\tSubtype: %s", message.SubType)
			*/

			msgQueue.Push(message.Timestamp)
			toDelete := msgQueue.Poll().(string)
			//logging.Log.Debugf("(%s) Adding to queue: %s; Removing from queue: %s", channelID, message.Timestamp, toDelete)
			api.DeleteMessage(channelID, toDelete)

		}
	}

	return
}
开发者ID:project8,项目名称:swarm,代码行数:42,代码来源:SlackMonitor.go

示例9: post

//TODO return after sending request immediately
func post(url string, payload io.Reader, cond *sync.Cond, ratio int, ready chan bool) {
	cond.L.Lock()
	ready <- true
	cond.Wait()
	cond.L.Unlock()

	log.Printf("++post: %s", url)

	u := url

	if !strings.HasPrefix(u, "http://") {
		u = "http://" + u
	}

	if !strings.HasSuffix(u, "/") {
		u = u + "/"
	}

	u = u + "download"

	resp, err := http.Post(u, "application/json", payload)
	if err != nil {
		log.Printf("post to %s error: %s", url, err.Error())
		return
	}

	if resp.StatusCode != 200 {
		log.Printf("post to %s error, status code %d", url, resp.StatusCode)
		return
	}

	log.Printf("--post: %s", url)

	for i := 0; i < ratio; i++ {
		cond.L.Lock()
		cond.Signal()
		cond.L.Unlock()
	}
}
开发者ID:ywk253100,项目名称:registry_p2p,代码行数:40,代码来源:batch.go

示例10: finishWaiting

func finishWaiting(cond *sync.Cond, waitFinished <-chan struct{}) {
	runtime.Gosched()
	select {
	// avoid creating a timer if we can help it...
	case <-waitFinished:
		return
	default:
		const spinTimeout = 100 * time.Millisecond
		t := time.NewTimer(spinTimeout)
		defer t.Stop()
		for {
			runtime.Gosched()
			cond.Broadcast()
			select {
			case <-waitFinished:
				return
			case <-t.C:
				t.Reset(spinTimeout)
			}
		}
	}
}
开发者ID:CodeJuan,项目名称:kubernetes,代码行数:22,代码来源:delay.go

示例11: sendRequest

func sendRequest(numReq int64, st *stats, ch chan bool, cd *sync.Cond) {
	cd.L.Lock()
	for status == false {
		cd.Wait()
	}
	resTime := []int64{}
	totReq := numReq
	for numReq > 0 {
		start := time.Now()
		resp, err := http.Get(queryuri)
		end := int64(time.Since(start))
		resTime = append(resTime, end)
		if err != nil {
			fmt.Println("Error is err", err, "response is ", resp, "restime is", resTime)
			st.failures++
		}
		ioutil.ReadAll(resp.Body)
		resp.Body.Close()
		numReq--
	}
	//time.Sleep(1*time.Second)
	var tot, max, min int64
	for _, val := range resTime {
		tot += val
		if val > max {
			max = val
		}
		if val < min {
			min = val
		}
	}
	st.totalTime = tot
	st.avgTime = tot / totReq
	st.maxTime = max
	st.minTime = min
	cd.L.Unlock()
	ch <- true
}
开发者ID:nimishzynga,项目名称:query_perf,代码行数:38,代码来源:query.go

示例12: TestRaceCond

func TestRaceCond(t *testing.T) { // tsan's test50
	ch := make(chan bool, 2)

	var x int = 0
	var mu sync.Mutex
	var condition int = 0
	var cond *sync.Cond = sync.NewCond(&mu)

	var waker func() = func() {
		<-time.After(1e5)
		x = 1
		mu.Lock()
		condition = 1
		cond.Signal()
		mu.Unlock()
		<-time.After(1e5)
		mu.Lock()
		x = 3
		mu.Unlock()
		ch <- true
	}

	var waiter func() = func() {
		mu.Lock()
		for condition != 1 {
			cond.Wait()
		}
		mu.Unlock()
		x = 2
		ch <- true
	}
	x = 0
	go waker()
	go waiter()
	<-ch
	<-ch
}
开发者ID:timnau,项目名称:golang,代码行数:37,代码来源:sync_test.go

示例13: RunTasksWithTimeout

func (tasks Tasks) RunTasksWithTimeout(stopTime time.Time) {
	finishedTasks := 0
	waitCond := new(sync.Cond)
	waitCond.L = new(sync.Mutex)

	done := make(chan bool, 1)
	current_running := 0
	for _, task := range tasks {

		waitCond.L.Lock()
		for current_running >= numWorkers {
			waitCond.Wait()
		}
		current_running++
		waitCond.L.Unlock()

		go func(task *Task) {
			todo := len(tasks) - finishedTasks - (numWorkers - 1)
			if todo < 1 {
				todo = 1
			}
			duration := stopTime.Sub(time.Now()) / time.Duration(todo)
			dprint(duration)
			task.stopTime = time.Now().Add(duration)
			go task.Run()
			<-task.ch
			if task.timed_out {
				dprint("Timeout occured.")
			} else {
				dprint("Finished normally.")
			}

			waitCond.L.Lock()
			current_running--
			finishedTasks++
			if finishedTasks == len(tasks) {
				done <- true
			}
			waitCond.Signal()
			waitCond.L.Unlock()
		}(task)
	}
	<-done
}
开发者ID:Tethik,项目名称:SeamlessIntegerFactorization,代码行数:44,代码来源:tasks.go

示例14: main

func main() {
	runtime.GOMAXPROCS(1)
	debug.SetGCPercent(1000000) // only GC when we ask for GC

	var stats, stats1, stats2 runtime.MemStats

	release := func() {}
	for i := 0; i < 20; i++ {
		if i == 10 {
			// Should be warmed up by now.
			runtime.ReadMemStats(&stats1)
		}

		c := make(chan int)
		for i := 0; i < 10; i++ {
			go func() {
				select {
				case <-c:
				case <-c:
				case <-c:
				}
			}()
		}
		time.Sleep(1 * time.Millisecond)
		release()

		close(c) // let select put its sudog's into the cache
		time.Sleep(1 * time.Millisecond)

		// pick up top sudog
		var cond1 sync.Cond
		var mu1 sync.Mutex
		cond1.L = &mu1
		go func() {
			mu1.Lock()
			cond1.Wait()
			mu1.Unlock()
		}()
		time.Sleep(1 * time.Millisecond)

		// pick up next sudog
		var cond2 sync.Cond
		var mu2 sync.Mutex
		cond2.L = &mu2
		go func() {
			mu2.Lock()
			cond2.Wait()
			mu2.Unlock()
		}()
		time.Sleep(1 * time.Millisecond)

		// put top sudog back
		cond1.Broadcast()
		time.Sleep(1 * time.Millisecond)

		// drop cache on floor
		runtime.GC()

		// release cond2 after select has gotten to run
		release = func() {
			cond2.Broadcast()
			time.Sleep(1 * time.Millisecond)
		}
	}

	runtime.GC()

	runtime.ReadMemStats(&stats2)

	if int(stats2.HeapObjects)-int(stats1.HeapObjects) > 20 { // normally at most 1 or 2; was 300 with leak
		print("BUG: object leak: ", stats.HeapObjects, " -> ", stats1.HeapObjects, " -> ", stats2.HeapObjects, "\n")
	}
}
开发者ID:Xiahl1990,项目名称:go,代码行数:73,代码来源:issue9110.go

示例15: cleanHistory

func cleanHistory(channelID string, api *slack.Client, msgQueue *utility.Queue, histSize int, histCond *sync.Cond, threadWait *sync.WaitGroup) {
	defer threadWait.Done()
	defer histCond.Signal()

	histCond.L.Lock()
	defer histCond.L.Unlock()

	logging.Log.Infof("(%s) Starting cleanHistory", channelID)
	histParams := slack.NewHistoryParameters()
	histParams.Inclusive = true

	histCountMax := 1000

	// build history with histSize messages
	logging.Log.Infof("(%s) Building history with %v messages", channelID, histSize)
	var history *slack.History
	var histErr error
	nRemaining := histSize
	for nRemaining > 0 {
		if nRemaining > histCountMax {
			histParams.Count = histCountMax
		} else {
			histParams.Count = nRemaining
		}

		history, histErr = api.GetChannelHistory(channelID, histParams)
		if histErr != nil {
			logging.Log.Errorf("(%s) Unable to get the channel history: %v", channelID, histErr)
			return
		}

		iLastMsg := len(history.Messages) - 1
		//logging.Log.Debug("0: %v, %v: %v", history.Messages[0].Timestamp, iLastMsg, history.Messages[iLastMsg].Timestamp)

		logging.Log.Debugf("(%s) In skip loop; obtained history with %v messages", channelID, len(history.Messages))

		for iMsg := iLastMsg; iMsg >= 0; iMsg-- {
			msgQueue.Push(history.Messages[iMsg].Timestamp)
			//logging.Log.Debugf("(%s) Pushing to queue: %s", channelID, history.Messages[iMsg].Timestamp)
		}

		if !history.HasMore {
			return
		}
		histParams.Latest = history.Messages[iLastMsg].Timestamp
		histParams.Inclusive = false
		nRemaining -= histCountMax
	}

	histParams.Count = histCountMax
	nDeleted := 0
	for history.HasMore == true {
		history, histErr = api.GetChannelHistory(channelID, histParams)
		if histErr != nil {
			logging.Log.Errorf("(%s) Unable to get the channel history: %v", channelID, histErr)
			return
		}

		logging.Log.Debugf("(%s) Deleting %v items (latest: %v)", channelID, len(history.Messages), history.Latest)

		for _ /*iMsg*/, message := range history.Messages {
			//logging.Log.Debugf("(%s) Deleting: %s", channelID, message.Timestamp)
			_, _ /*respChan, respTS,*/, respErr := api.DeleteMessage(channelID, message.Timestamp)
			if respErr != nil {
				logging.Log.Warningf("(%s) Unable to delete message: %v", channelID, respErr)
			}
			//logging.Log.Debugf("(%s) Deletion response: %s, %s, %v", channelID, respChan, respTS, respErr)
			nDeleted++
		}
		histParams.Latest = history.Messages[len(history.Messages)-1].Timestamp
	}
	logging.Log.Noticef("(%s) Deleted %v messages", channelID, nDeleted)

	return
}
开发者ID:project8,项目名称:swarm,代码行数:75,代码来源:SlackMonitor.go


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