Skip to content

Commit

Permalink
sync.Atomic utility
Browse files Browse the repository at this point in the history
  • Loading branch information
aditya43 committed May 30, 2021
1 parent 5abd6e5 commit 9d54ff1
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
30 changes: 30 additions & 0 deletions 04-sync-package/02-automic/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package main

import (
"fmt"
"runtime"
"sync"
"sync/atomic"
)

func main() {
runtime.GOMAXPROCS(4)

var counter uint64
var wg sync.WaitGroup

// implement concurrency safe counter

for i := 0; i < 50; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for c := 0; c < 1000; c++ {
// counter++
atomic.AddUint64(&counter, 1)
}
}()
}
wg.Wait()
fmt.Println("counter: ", counter)
}
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,3 +273,9 @@ select {
* Communicating asynchronous results.
- Mutex:
* When we have data such as Caches, States, Registeries which are big to be sent over the channels and we want access to this data to be thread safe. This is where classic synchronization tool such as Mutex comes into the picture.

-----------

## 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.

0 comments on commit 9d54ff1

Please sign in to comment.