Do1phln
发布于 2022-10-10 / 10 阅读
0
0

golang并发编程示例小记

golang并发编程示例小记

Go提供了sync和channel两种方式来支持协程的并发

0x00 sync

如果我们希望并发下载N个资源,多个并发协程之间不需要通信,那么就可以使用sync.WaitGroup,等待所有并发协程执行结束

package main

import (
	"fmt"
	"sync"
	"time"
)

var wg sync.WaitGroup

func download(url string){
	fmt.Println("start downloading:", url)
	time.Sleep(time.Second)//模拟耗时
	fmt.Println(url + "OK!")
	wg.Done()
}

func main(){
	for i := 0;i<10;i++{
		wg.Add(1)
		go download("a.com/" + string(i+'0'))
	}
	fmt.Println("waiting...")
	wg.Wait()
	fmt.Println("Done!")
}

//waiting...
//start downloading: a.com/7
//start downloading: a.com/2
//start downloading: a.com/1
//start downloading: a.com/5
//start downloading: a.com/3
//start downloading: a.com/0
//start downloading: a.com/4
//start downloading: a.com/8
//start downloading: a.com/6
//start downloading: a.com/9
//a.com/1OK!
//a.com/0OK!
//a.com/5OK!
//a.com/3OK!
//a.com/7OK!
//a.com/2OK!
//a.com/8OK!
//a.com/6OK!
//a.com/9OK!
//a.com/4OK!
//Done!
  • wg.Add(1)表示为wg添加一个计数,wg.Done()减去一个计数
  • go download()表示启动新的协程并发执行download函数
  • wg.Wait()等待所有协程执行结束

可以看到原来需要10s的并发操作,并发后约1-2s即可执行完毕

0x01 channel

package main

import (
	"fmt"
	"sync"
	"time"
)

var wg sync.WaitGroup

var ch = make(chan string, 10)//创建大小为10的缓冲信道

func download(url string){
	fmt.Println("start downloading:", url)
	time.Sleep(time.Second)//模拟耗时
	fmt.Println(url + " OK!")
	ch <- url
}

func main(){
	for i := 0;i<10;i++{
		go download("a.com/" + string(i+'0'))
	}
	for i:=0;i<10;i++{
		msg:=<-ch//等待信道返回消息
		fmt.Println("finish: ", msg)
	}
	//fmt.Println("waiting...")
	//wg.Wait()
	fmt.Println("Done!")
}

//start downloading: a.com/9
//start downloading: a.com/2
//start downloading: a.com/5
//start downloading: a.com/7
//start downloading: a.com/0
//start downloading: a.com/8
//start downloading: a.com/6
//start downloading: a.com/1
//start downloading: a.com/3
//start downloading: a.com/4
//a.com/4 OK!
//a.com/5 OK!
//a.com/9 OK!
//a.com/1 OK!
//a.com/7 OK!
//a.com/0 OK!
//a.com/3 OK!
//a.com/6 OK!
//a.com/8 OK!
//finish:  a.com/4
//finish:  a.com/5
//finish:  a.com/9
//finish:  a.com/1
//finish:  a.com/7
//finish:  a.com/0
//finish:  a.com/3
//finish:  a.com/6
//finish:  a.com/8
//a.com/2 OK!
//finish:  a.com/2
//Done!

使用channel信道,可以在协程之间传递消息,阻塞等待并发协程返回消息


评论