码迷,mamicode.com
首页 > 其他好文 > 详细

golang同步示例代码

时间:2020-06-07 14:40:03      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:code   write   make   add   lock   tab   imp   base   pack   

`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同步示例代码

标签:code   write   make   add   lock   tab   imp   base   pack   

原文地址:https://www.cnblogs.com/warrior-tian/p/13060437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!