Go: 10-2 传统同步机制

检测数据冲突
传统同步机制
 package main
 
 import (
 	"fmt"
 	"sync"
 )
 
 func doWork(id int,
 	w worker) {
 	for n := range w.in {
 		fmt.Printf("Worker %d received %c\n",
 			id, n)
 		w.done()
 	}
 }
 
 type worker struct {
 	in   chan int
 	done func()
 }
 
 func createWorker(
 	id int, wg *sync.WaitGroup) worker {
 	w := worker{
 		in: make(chan int),
 		done: func() {
 			wg.Done()
 		},
 	}
 	go doWork(id, w)
 	return w
 }
 
 func chanDemo() {
 	var wg sync.WaitGroup
 
 	var workers [10]worker
 	for i := 0; i < 10; i++ {
 		workers[i] = createWorker(i, &wg)
 	}
 
 	wg.Add(20)
 	for i, worker := range workers {
 		worker.in <- 'a' + i
 	}
 	for i, worker := range workers {
 		worker.in <- 'A' + i
 	}
 
 	wg.Wait()
 }
 
 func main() {
 	chanDemo()
 }
 

//加锁之前
package main

import (
	"fmt"
	"time"
)

type atomicInt int

func (a *atomicInt) increment() {
	*a++
}

func (a *atomicInt) get() int {
	return int(*a)
}

func main() {
	var a atomicInt
	a.increment()
	go func() {
		a.increment()
	}()
	time.Sleep(time.Millisecond)
	fmt.Println(a)
}
----------------------------------------------------------------------------------------
//加锁之后
package main

import (
	"fmt"
	"sync"
	"time"
)

type atomicInt struct {
	value int
	lock  sync.Mutex
}

func (a *atomicInt) increment() {
	a.lock.Lock()
	defer a.lock.Unlock()
	a.value++
}

func (a *atomicInt) get() int {
	a.lock.Lock()
	defer a.lock.Unlock()
	return a.value
}

func main() {
	var a atomicInt
	a.increment()
	go func() {
		a.increment()
	}()
	time.Sleep(time.Millisecond)
	fmt.Println(a.get())
}