From 39b16e4c6ae13f5dd93164e5be1660110cad8815 Mon Sep 17 00:00:00 2001 From: "jian.han" Date: Fri, 12 Jan 2018 14:27:12 +1000 Subject: [PATCH] added atomic functions --- concurrency/atomic_functions/main.go | 36 +++++++++++++++++++ .../mastering_concurrency_in_go/ch3/main.go | 21 +++++++++++ .../mastering_concurrency_in_go/main.go | 9 ----- defer/main.go | 6 ++++ 4 files changed, 63 insertions(+), 9 deletions(-) create mode 100644 concurrency/atomic_functions/main.go create mode 100644 concurrency/mastering_concurrency_in_go/ch3/main.go delete mode 100644 concurrency/mastering_concurrency_in_go/main.go diff --git a/concurrency/atomic_functions/main.go b/concurrency/atomic_functions/main.go new file mode 100644 index 0000000..175dc49 --- /dev/null +++ b/concurrency/atomic_functions/main.go @@ -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() + } +} diff --git a/concurrency/mastering_concurrency_in_go/ch3/main.go b/concurrency/mastering_concurrency_in_go/ch3/main.go new file mode 100644 index 0000000..4082d63 --- /dev/null +++ b/concurrency/mastering_concurrency_in_go/ch3/main.go @@ -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) + } +} diff --git a/concurrency/mastering_concurrency_in_go/main.go b/concurrency/mastering_concurrency_in_go/main.go deleted file mode 100644 index ffd8cc0..0000000 --- a/concurrency/mastering_concurrency_in_go/main.go +++ /dev/null @@ -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() -} diff --git a/defer/main.go b/defer/main.go index 2107a62..24f1ff4 100644 --- a/defer/main.go +++ b/defer/main.go @@ -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() }