Skip to content

Commit 4088873

Browse files
authored
Add semaphore example. (#89)
1 parent fd8f9c1 commit 4088873

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

advanced/semaphore.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

0 commit comments

Comments
 (0)