Skip to content

Commit ffa931d

Browse files
committed
adding some basics around sync.WorkGroup
1 parent b148753 commit ffa931d

File tree

2 files changed

+98
-0
lines changed

2 files changed

+98
-0
lines changed

concurrency/channels.go

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"time"
6+
)
7+
8+
/*
9+
Similar to maps, channels are a reference type are are allocated with `make`. If an optional
10+
integer is provided, the channel is considered a buffered channel. Channels without a buffer
11+
set are known as synchronous, or unbuffered channels.
12+
13+
Channels combine communicate with synchronization, guaranteeing that multiple goroutines are
14+
in a known state.
15+
*/
16+
17+
func longRunningFunction(delay int) int {
18+
fmt.Printf("Sleeping for %d seconds.", delay)
19+
time.Sleep(time.Duration(delay) * time.Second)
20+
return delay
21+
}
22+
23+
func channelBlockingOnGoroutines() int {
24+
theChannel := make(chan int)
25+
go func() {
26+
theChannel <- longRunningFunction(3)
27+
}()
28+
return <-theChannel
29+
30+
}
31+
32+
func main() {
33+
// Build an unbuffered channel of integers
34+
basicChannel := make(chan int)
35+
// Build a unbuffered/sync channel of strings
36+
// This is the same under the hood as `basicChannel` above.
37+
basicSyncChannel := make(chan string, 0)
38+
// Build a buffered channel of size 10 of strings
39+
basicBufferedChannel := make(chan string, 10)
40+
41+
// close the channels
42+
close(basicChannel)
43+
close(basicSyncChannel)
44+
close(basicBufferedChannel)
45+
46+
channelBlockingOnGoroutines()
47+
48+
}

concurrency/waitgroups.go

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"sync"
6+
"time"
7+
)
8+
9+
func delaySeconds(seconds int) {
10+
total := time.Duration(seconds) * time.Second
11+
fmt.Printf("Delaying for %d seconds. \n", int64(total.Seconds()))
12+
time.Sleep(total)
13+
}
14+
15+
func intenseWorkload(delay int, wg *sync.WaitGroup) {
16+
defer wg.Done()
17+
delaySeconds(5)
18+
go subWorkloadOne(wg)
19+
go subWorkloadTwo(wg)
20+
go subWorkloadThree(wg)
21+
}
22+
23+
func subWorkloadOne(wg *sync.WaitGroup) {
24+
defer wg.Done()
25+
delaySeconds(3)
26+
}
27+
28+
func subWorkloadTwo(wg *sync.WaitGroup) {
29+
defer wg.Done()
30+
delaySeconds(3)
31+
32+
}
33+
34+
func subWorkloadThree(wg *sync.WaitGroup) {
35+
defer wg.Done()
36+
delaySeconds(3)
37+
}
38+
39+
func main() {
40+
start := time.Now()
41+
wg := sync.WaitGroup{}
42+
for i := 0; i < 5; i++ {
43+
wg.Add(4)
44+
go intenseWorkload(5, &wg)
45+
}
46+
wg.Wait()
47+
dur := time.Since(start)
48+
fmt.Printf("Executing in %d seconds", int64(dur.Seconds()))
49+
50+
}

0 commit comments

Comments
 (0)