首页 > 代码库 > Go语言,互斥锁使用

Go语言,互斥锁使用

package mainimport (	"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语言,互斥锁使用