Skip to content

Commit

Permalink
sync.Cond Signal
Browse files Browse the repository at this point in the history
  • Loading branch information
aditya43 committed May 30, 2021
1 parent 9d54ff1 commit 3ed40c7
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
38 changes: 38 additions & 0 deletions 04-sync-package/03-cond-signal/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"fmt"
"sync"
)

var sharedRsc = make(map[string]interface{})

func main() {
var wg sync.WaitGroup

mu := sync.Mutex{}
cond := sync.NewCond(&mu)

wg.Add(1)
go func() {
defer wg.Done()

// suspend goroutine until sharedRsc is populated.
cond.L.Lock()
for len(sharedRsc) == 0 {
// time.Sleep(1 * time.Millisecond)
cond.Wait()
}

fmt.Println(sharedRsc["rsc1"])
cond.L.Unlock()
}()

cond.L.Lock()
// writes changes to sharedRsc
sharedRsc["rsc1"] = "foo"
cond.Signal()
cond.L.Unlock()

wg.Wait()
}
23 changes: 22 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,4 +278,25 @@ select {

## sync.Atomic:
- `Automic` is used to performed low level automic operations on memory. It is used by other synchonization utilities.
- It is a `lockless` operation.
- It is a `lockless` operation.

-----------

## sync.Cond:
- Condition variable is one of the synchronization mechanism.
- It is a `lockless` operation.
- A condition variable is basically a container of Goroutines that are waiting for a certain condition.
- Condition variables are type:
```go
var c *sync.Cond
```
- We use constructor method `sync.NewCond()` to create a conditional variable, it takes `sync.Locker` interface as input, which is usually `sync.Mutex`.
```go
mu := sync.Mutex{}
cond := sync.NewCond(&mu)
```
- Wait suspends the execution of Goroutine.
- Signal wakes one Goroutine waiting on `c`.
- Broadcast wakes all Goroutines waiting on `c`.

-----------

0 comments on commit 3ed40c7

Please sign in to comment.