Skip to content

Commit

Permalink
add cond implementation using a channel
Browse files Browse the repository at this point in the history
  • Loading branch information
steevehook committed Sep 5, 2021
1 parent 31ccc86 commit 0a08fcd
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
File renamed without changes.
37 changes: 37 additions & 0 deletions mutexes/cond/cond-implementation/channel/main.go
@@ -0,0 +1,37 @@
package main

import "sync"

func main() {
}

type cond struct {
L sync.Mutex // used by caller
mu sync.Mutex // guards ch
ch chan struct{}
}

func (c *cond) Wait() {
c.mu.Lock()
ch := c.ch
c.mu.Unlock()
c.L.Unlock()
<-ch
c.L.Lock()
}

func (c *cond) Signal() {
c.mu.Lock()
defer c.mu.Unlock()
select {
case c.ch <- struct{}{}:
default:
}
}

func (c *cond) Broadcast() {
c.mu.Lock()
defer c.mu.Unlock()
close(c.ch)
c.ch = make(chan struct{})
}

0 comments on commit 0a08fcd

Please sign in to comment.