go-concurrency101/6-lock-with-channel/main.go

29 lines
463 B
Go

package main
import (
"fmt"
"time"
)
/*
@Ref: https://livebook.manning.com/book/go-in-practice/chapter-3/65
*/
func main() {
lock := make(chan bool, 1)
for i := 1; i < 7; i++ {
go worker(i, lock)
}
time.Sleep(10 * time.Second)
}
func worker(id int, lock chan bool) {
fmt.Printf("%d wants the lock\n", id)
lock <- true
fmt.Printf("%d has the lock\n", id)
time.Sleep(500 * time.Millisecond)
fmt.Printf("%d is releasing the lock\n", id)
<-lock
}