Skip to content

Instantly share code, notes, and snippets.

@Petelin Petelin/condition.go
Last active Mar 21, 2019

Embed
What would you like to do?
三个线程顺序打印ABC
package main
import (
"fmt"
"sync"
"time"
)
var l = sync.Mutex{}
var cond = sync.NewCond(&l)
var turn = 0
func main() {
s := []string{"A", "B", "C"}
for _, item := range s {
go func(x string) {
for i := 0; i < 10; i++ {
//fmt.Println("try get lock ", x)
l.Lock()
for s[turn] != x {
cond.Wait()
}
// my turn
fmt.Println(i, x)
turn = (turn + 1) % 3
cond.Broadcast()
cond.Wait()
l.Unlock()
}
}(item)
}
time.Sleep(time.Hour)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.