golang同步示例代码
Posted warrior-tian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang同步示例代码相关的知识,希望对你有一定的参考价值。
`package main
import (
"fmt"
"sync"
"time"
)
func ReadDB(wg *sync.WaitGroup, Chsignsl chan int, rm *sync.RWMutex) {
Chsignsl <- 123
rm.RLock()
fmt.Println("reading database....")
<-time.After(1)
rm.RUnlock()
<-Chsignsl
wg.Done()
}
func WriteDB(wg *sync.WaitGroup, Chsignsl chan int, rm *sync.RWMutex) {
Chsignsl <- 123
rm.Lock()
fmt.Println("writting database....")
timer := time.NewTicker(time.Second)
for i := 0; i < 1; i++ {
<-timer.C
}
rm.Unlock()
<-Chsignsl
wg.Done()
}
func main() {
var wg sync.WaitGroup
var rmt sync.RWMutex
Chsignsl := make(chan int, 5)
for i := 0; i < 10; i++ {
for i := 0; i < 3; i++ {
wg.Add(1)
go ReadDB(&wg, Chsignsl, &rmt)
}
wg.Add(1)
go WriteDB(&wg, Chsignsl, &rmt)
}
wg.Wait()
fmt.Println("主协程结束...")
}
`
以上是关于golang同步示例代码的主要内容,如果未能解决你的问题,请参考以下文章