12Sep2022
Golang¶
Go Synchronization primitives:
- Locks -- Enables communication through shared data
- Channels -- Enables communication through thread channels
Terms * goroutine * periodic task - go routines + Added sleep * Mutex lock * Weight Group
Condition Variable: Whenever we have some shared data, and we have some condition check on those data, it is recommended to use Condition variable. Condition variable provides two new methods (Brodcast, Wait). Wait() will wait for the condition variable to broadcast() to proceed f forward. Generally, you would had to sleep for sometime and wake up and check if any chance has been made to condition variables. This can be avoided with condition variable.
Pattern:
mu.Lock()
//do somethign that affect the condition
cond.Broadcast()
mu.Unlock()
-----
mu.Lock()
while condition == false{
cond.Wait()
}
//now condition is true, and we have the lock
mu.Unlock()
Channels: * These happend syncronously. If some sender/reciever doesn't exist, it will block the thread and keep waiting. Can cause deadlock. When are channels useful? -> Producer & Consumer Queue. Someone producing the tasks and someone listening the task. -> Replacement of WaitGroups
Try avoiding channels. Use shared memory, mutex or condition variables etc instead, as they are easier to reason about.
WaitGroup
package main
import "sync"
func main(){
var wg sync.WaitGroup
for i:=0; i< 5;i++ {
wg.Add(1)
go func(x int){
sendRpc(x)
wg.Done()
}(i)
}
wg.Wait()
}