Skip to content

Commit

Permalink
sync Once | Singletons
Browse files Browse the repository at this point in the history
  • Loading branch information
aditya43 committed May 30, 2021
1 parent 43a15b5 commit 60721e8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
27 changes: 27 additions & 0 deletions 04-sync-package/05-sync-once/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import (
"fmt"
"sync"
)

func main() {
var wg sync.WaitGroup
var once sync.Once

load := func() {
fmt.Println("Run only once initialization function")
}

wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()

// modify so that load function gets called only once.
// load()
once.Do(load)
}()
}
wg.Wait()
}
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,4 +299,9 @@ cond := sync.NewCond(&mu)
- Signal wakes one Goroutine waiting on `c`.
- Broadcast wakes all Goroutines waiting on `c`.

-----------
-----------

## sync.Once:
- `sync.Once` is used to run one time initialization functions.
- `once.Do(funcValue)` method accepts the initialization function.
- `sync.Once` ensures that only one call to `Do` ever calls the function that is passed in - even on different Goroutines.

0 comments on commit 60721e8

Please sign in to comment.