added atomic functions

This commit is contained in:
jian.han 2018-01-12 14:27:12 +10:00
parent 9b491561e5
commit 39b16e4c6a
4 changed files with 63 additions and 9 deletions

View 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()
}
}

View 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)
}
}

View File

@ -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()
}

View File

@ -12,6 +12,12 @@ func nilFuncDefer() {
fmt.Println("runs") 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() { func main() {
nilFuncDefer() nilFuncDefer()
} }