Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add cond implementation using a channel
- Loading branch information
1 parent
31ccc86
commit 0a08fcd
Showing
2 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
File renamed without changes.
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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{}) | ||
} |