1. 程式人生 > >Go語言,互斥鎖使用

Go語言,互斥鎖使用

class creat brush true tin clas pre unlock defer

package main

import (
	"fmt"
	"runtime"
	"sync"
)

var (
	counter int
	wg sync.WaitGroup
	mutex sync.Mutex
)

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++ {
		mutex.Lock()
		{
			value := counter
			runtime.Gosched()
			value++
			counter = value
		}
		mutex.Unlock()
	}
}

  

Go語言,互斥鎖使用