Skip to content

Instantly share code, notes, and snippets.

@smagch
Last active December 15, 2015 02:18
Show Gist options
  • Save smagch/5185828 to your computer and use it in GitHub Desktop.
Save smagch/5185828 to your computer and use it in GitHub Desktop.
sync.Cond test
package main
import (
"log"
"time"
"sync"
)
const NUM = 2
var finished = make(chan bool, NUM)
func tomTask(cond *sync.Cond) {
cond.L.Lock()
log.Println(`Tom:
I locked a room. George won't be able to do task.
because I locked the room which can accommodate only one person.
`)
time.Sleep(2 * time.Second)
log.Println(`Tom:
I got some stuff to do. I'm going to let George know that
he can use this room.
I will do remaining tasks after Gerge finished.
`)
cond.Wait()
log.Print(`Tom:
Thanks George.
I'm going to work on remaining tasks.
`)
time.Sleep(2 * time.Second)
log.Println(`Tom:
finished!
`)
cond.L.Unlock()
finished <- true
}
func georgeTask(cond *sync.Cond) {
log.Println(`George:
Ah, Tom is using the room.
I can't do my task when Tom is using the room.
`)
cond.L.Lock()
log.Println(`George:
Thanks Tom. I'll let you know when I finish.
Let's get started with my work!
`)
time.Sleep(2 * time.Second)
log.Println(`George:
finished!
`)
cond.L.Unlock()
log.Println(`George:
I'm going to let Tom know that I've finished my task.
`)
cond.Signal()
finished <- true
}
func main() {
var m sync.Mutex
cond := sync.NewCond(&m)
go tomTask(cond)
go georgeTask(cond)
for i := 0; i < NUM; i++ {
<-finished
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment