Skip to content

Instantly share code, notes, and snippets.

@Petelin
Last active March 21, 2019 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Petelin/9fbb32125297343c86d63748688aa60e to your computer and use it in GitHub Desktop.
Save Petelin/9fbb32125297343c86d63748688aa60e to your computer and use it in GitHub Desktop.
三个线程顺序打印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