mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-22 04:36:02 +03:00
added atomic functions
This commit is contained in:
parent
9b491561e5
commit
39b16e4c6a
36
concurrency/atomic_functions/main.go
Normal file
36
concurrency/atomic_functions/main.go
Normal file
@ -0,0 +1,36 @@
|
||||
// This sample program demonstrates how to use the atomic
|
||||
// package to provide safe access to numeric types.
|
||||
|
||||
// Atomic functions provide low-level locking mechanisms for synchronizing access to
|
||||
// integers and pointers.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
var (
|
||||
counter int64
|
||||
|
||||
wg sync.WaitGroup
|
||||
)
|
||||
|
||||
func main() {
|
||||
wg.Add(2)
|
||||
go incCounter(1)
|
||||
go incCounter(2)
|
||||
wg.Wait()
|
||||
fmt.Println("Final Counter : ", counter)
|
||||
}
|
||||
|
||||
func incCounter(id int) {
|
||||
defer wg.Done()
|
||||
for count := 0; count < 2; count++ {
|
||||
atomic.AddInt64(&counter, 1)
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
21
concurrency/mastering_concurrency_in_go/ch3/main.go
Normal file
21
concurrency/mastering_concurrency_in_go/ch3/main.go
Normal file
@ -0,0 +1,21 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// demostration of channel and timeout
|
||||
func main() {
|
||||
ourChan := make(chan string, 1)
|
||||
|
||||
go func() {
|
||||
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-time.After(10 * time.Second):
|
||||
fmt.Println("Enough waiting")
|
||||
close(ourChan)
|
||||
}
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
package main
|
||||
|
||||
import "github.com/jianhan/go-patterns/concurrency/mastering_concurrency_in_go/ch1"
|
||||
|
||||
func main() {
|
||||
// ch1.Run()
|
||||
// ch1.RunLetter()
|
||||
ch1.RunSpider()
|
||||
}
|
@ -12,6 +12,12 @@ func nilFuncDefer() {
|
||||
fmt.Println("runs")
|
||||
}
|
||||
|
||||
// Do not use defer inside a loop unless you are sure about what you are doing. It may not work as expected.
|
||||
// However, in some situations it will be handy for instance,delegating the recursivity of a func to a defer.
|
||||
func deferInsideLoop() {
|
||||
|
||||
}
|
||||
|
||||
func main() {
|
||||
nilFuncDefer()
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user