您的位置 首页 golang

Golang实现并发控制案例

随笔记录,初次认识go协程的时候就会学习GMP并发模型,第一次上手编码的时候会用 go 关键子启动协程,做并发任务,运行过程中会出现主线程和go协程执行顺序的问题, 接下来我这边通过两个小小的案例,可以保证go协程执行完后并通知主线程做后续的工作。

WaitGroup

WaitGroup用于等待一组线程的结束。父线程调用Add方法来设定应等待的 线程 的数量。每个被等待的线程在结束时应调用Done方法。同时,主线程里可以调用Wait方法阻塞至所有线程结束。

waitgroup用法

 package main

 import  (
"net/http"
"sync"
)

func main() {
var wg sync.WaitGroup
var urls = []string{
"#34;,
"#34;,
}
for _, url := range urls {
// Increment the WaitGroup counter.
wg.Add(1)
// Launch a goroutine to fetch the URL.
go func(url string) {
// Decrement the counter when the goroutine completes.
defer wg.Done()
// Fetch the URL.
http.Get(url)
}(url)
}
// Wait for all HTTP fetches to complete.
wg.Wait()
}
  

Channel

实现两个协程分别去做写和读数据的工作,当读协程处理读数据后,通知主线程退出。

两个协程分别是写和读数据

 package main

import "fmt"

func main() {
intChan := make(chan int, 50)
exitChan := make(chan  bool , 1)

go writeData(50, intChan)
go readData(intChan, exitChan)

for {
_, ok := <-exitChan
if !ok {
break
}
}
}

func writeData(data int, intChan chan int) {
for i := 1; i < data; i++ {
intChan <- i
}
close(intChan)
}

func readData(queue chan int, exit chan bool) {
for {
v, ok := <-queue
if !ok {
break
}
fmt.Println(v)
}

exit <- true

}  

文章来源:智云一二三科技

文章标题:Golang实现并发控制案例

文章地址:https://www.zhihuclub.com/97115.shtml

关于作者: 智云科技

热门文章

网站地图