Skip to content

Anshul619/Concurrency-Go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Concurrency in GoLang

Constructs

Construct Package Description Sample Code
Mutex sync We can use a mutex to safely access data across multiple goroutines.
- Lock the mutex before accessing counters; unlock it at the end of the function using a defer statement.
- sync.RWMutex lets multiple goroutines read simultaneously (via RLock), but still enforces exclusive access for writes (Lock).
type Test struct { mu sync.Mutex }
- c.mu.Lock()
- defer c.mu.Unlock()
- c.counter++
WaitGroup sync A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add() to set the number of goroutines to wait for. var wg sync.WaitGroup
- wg.Add(1) // Always call wg.Add() before you launch the goroutine that will call wg.Done().
- wg.Done() //Recommended to call WaitGroup.Done() deferred, so it gets called even if the goroutine panics.
- wg.Wait() //wg.Wait() will block until wg.Done() is called.
Once sync Once is an object that will perform exactly one action. var once sync.Once
- once.Do(func() {singleInstance = new(single)})

References

About

This repo contains "how to to-dos", concurrency concepts in Go.

Topics

Resources

Stars

Watchers

Forks

Languages