Go语言-并发通信

前端之家收集整理的这篇文章主要介绍了Go语言-并发通信前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Go语言-并发通信

package main

import "fmt"
import "sync"
import "runtime"

var counter int = 0

func Count(lock *sync.Mutex) {
	lock.Lock()
	counter++
	fmt.Println(counter)
	lock.Unlock()
}
func main() {
	lock := &sync.Mutex{}
	for i := 0; i < 10; i++ {
		go Count(lock)
	}
	for {
		lock.Lock()
		c := counter
		lock.Unlock()
		runtime.Gosched()
		if c >= 10 {
			break
		}
	}
}

在线演示

https://c.runoob.com/compile/21

猜你在找的Go相关文章