go sync的并发同步简单用法

来源:互联网 发布:小说有声阅读软件 编辑:程序博客网 时间:2024/06/06 02:11
//通过golang中的 goroutine 与sync.Mutex进行并发同步
package main
import (
    "fmt"
    "runtime"
    "sync"
)
var count int = 0
func counter(lock *sync.Mutex) {
    lock.Lock()
    count++
    fmt.Println(count)
    lock.Unlock()
}
func main() {
    lock := &sync.Mutex{} //传递指针是为了防止 函数内的锁和 调用锁不一致
    for i := 0; i < 100000; i++ {
        go counter(lock)
    }
    for {
        lock.Lock()
        c := count
        lock.Unlock()
        runtime.Gosched() //把时间片给别的goroutine  未来某个时刻运行该routine
        if c >= 100000 {
            fmt.Println("gorountine end")
            break
        }
    }
}
 
原创粉丝点击