下一步应该是互斥锁了。
package main import ( "fmt" "runtime" "sync" "sync/atomic" ) var ( counter int64 wg sync.WaitGroup ) func main() { wg.Add(2) fmt.Println("Create Goroutines") go incCounter(1) go incCounter(2) fmt.Println("Waiting To Finish") 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() } }
时间: 2024-11-09 04:00:12