go sync的并发同步简单用法
发布时间:2020-12-16 18:07:31 所属栏目:大数据 来源:网络整理
导读://通过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() { lo
//通过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
}
}
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |