Methods to control the number of concurrency in go language

Release: 2020-06-17 17:48:47
forward
3262 people have browsed it

Methods to control the number of concurrency in go language

Because the Go language supports concurrency, concurrency questions are often asked in interviews. For example, what are the ways to control the number of go concurrencies? The following are two examples that I personally compiled:

func waitGroup() { count := 10 wg := sync.WaitGroup{} for i := 0; i < count; i++ { wg.Add(1) go func(j int) { fmt.Print(j) wg.Done() // 也可使用 wg.Add(-1) }(i) } wg.Wait() }
Copy after login

The above mainly uses the waitGroup under the sync package in go. This is also a common implementation method at work. The key point is to grasp the Add method. Position, the Wait method is to wait for all coroutines to be executed

func channel() { count := 10 // 最大支持并发 sum := 100 // 任务总数 c := make(chan struct{}, count) // 控制任务并发的chan sc := make(chan struct{}, sum) // 控制任务总数的chan defer close(c) defer close(sc) for i:=0; i0;i-- { <- sc } }
Copy after login

The above example uses the channel in go, using the channel blocking feature and the buffered channel to control the number of concurrencies, where sc This channel can be removed. In the example, it is only used to prevent all output from not being output after the main program exits. In normal operation, the program is generally blocking, so it can be removed.

For more related knowledge, please pay attention to the go language tutorial column

The above is the detailed content of Methods to control the number of concurrency in go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!