Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "context"
- "fmt"
- "sync"
- "sync/atomic"
- "time"
- )
- var mutex = &sync.Mutex{}
- type Fib struct {
- a int64
- b int64
- timeStart int64
- timeEnd int64
- }
- func withMutex(ctx context.Context, fibbValue *Fib) {
- var a int64 = 0
- var b int64 = 1
- var aku int64 = 0
- for {
- select {
- case <-ctx.Done():
- return
- default:
- mutex.Lock()
- a = fibbValue.a
- b = fibbValue.b
- mutex.Unlock()
- aku = b
- b = a + b
- a = aku
- if (b < 0) {
- mutex.Lock()
- timeNow := time.Now().UnixNano()
- fibbValue.timeEnd = timeNow - fibbValue.timeStart
- mutex.Unlock()
- return
- }
- mutex.Lock()
- fibbValue.a = a
- fibbValue.b = b
- mutex.Unlock()
- }
- }
- }
- func withAtomic(ctx context.Context, fibbValue *Fib) {
- var a int64 = 0
- var b int64 = 1
- var aku int64 = 0
- for {
- select {
- case <-ctx.Done():
- return
- default:
- a = atomic.LoadInt64(&fibbValue.a)
- b = atomic.LoadInt64(&fibbValue.b)
- aku = b
- b = a + b
- a = aku
- if (b < 0) {
- mutex.Lock()
- timeNow := time.Now().UnixNano()
- fibbValue.timeEnd = timeNow - fibbValue.timeStart
- mutex.Unlock()
- return
- }
- atomic.StoreInt64(&fibbValue.a, a)
- atomic.StoreInt64(&fibbValue.b, b)
- }
- }
- }
- func main() {
- ctx := context.Background()
- ctxAtomic, cancelAtomic := context.WithCancel(ctx)
- timeNow := time.Now().UnixNano()
- fibbValue := Fib{a: 0, b: 1, timeStart: timeNow}
- go withAtomic(ctxAtomic, &fibbValue)
- go withAtomic(ctxAtomic, &fibbValue)
- go withAtomic(ctxAtomic, &fibbValue)
- go withAtomic(ctxAtomic, &fibbValue)
- time.Sleep(100 * time.Millisecond)
- cancelAtomic()
- fmt.Println("Done Atomic. Time [ns]:", fibbValue.timeEnd)
- ctxMutex, cancelMutex := context.WithCancel(ctx)
- timeNow = time.Now().UnixNano()
- fibbValue = Fib{a: 0, b: 1, timeStart: timeNow}
- go withMutex(ctxMutex, &fibbValue)
- go withMutex(ctxMutex, &fibbValue)
- go withMutex(ctxMutex, &fibbValue)
- go withMutex(ctxMutex, &fibbValue)
- time.Sleep(100 * time.Millisecond)
- cancelMutex()
- fmt.Println("Done Mutex. Time [ns]:", fibbValue.timeEnd)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement