Last active
March 21, 2019 10:41
-
-
Save Petelin/9fbb32125297343c86d63748688aa60e to your computer and use it in GitHub Desktop.
三个线程顺序打印ABC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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