File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ package main
2+
3+ // This example shows how easy it is to implement a semaphore using channels.
4+ // A semaphore can be used to limit the number of concurrent go routines executing a task.
5+
6+ import (
7+ "fmt"
8+ "sync"
9+ "time"
10+ )
11+
12+ func main () {
13+ const maxConcurrent = 2
14+
15+ const totalTasks = 10
16+
17+ semaphore := make (chan struct {}, maxConcurrent )
18+
19+ wg := sync.WaitGroup {}
20+
21+ for i := range make ([]int , totalTasks ) {
22+ // blocks until semaphore is released
23+ semaphore <- struct {}{}
24+
25+ taskNumber := i
26+ // executes task async
27+ wg .Add (1 )
28+ go func () {
29+ defer func () {
30+ wg .Done ()
31+ // release semaphore
32+ <- semaphore
33+ }()
34+
35+ fmt .Println ("executing task: " , taskNumber )
36+ time .Sleep (time .Second )
37+ }()
38+ }
39+
40+ wg .Wait ()
41+
42+ fmt .Println ("done" )
43+ }
You can’t perform that action at this time.
0 commit comments