-
Notifications
You must be signed in to change notification settings - Fork 0
/
waitgroup_example_test.go
61 lines (49 loc) · 1.01 KB
/
waitgroup_example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package async_test
import (
"fmt"
"sync"
"time"
"github.com/b97tsk/async"
)
func ExampleWaitGroup() {
var wg sync.WaitGroup // For keeping track of goroutines.
var myExecutor async.Executor
myExecutor.Autorun(func() {
wg.Add(1)
go func() {
defer wg.Done()
myExecutor.Run()
}()
})
var myState struct {
wg async.WaitGroup
v1, v2 int
}
myState.wg.Add(2) // Note that async.WaitGroup is not safe for concurrent use.
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(500 * time.Millisecond) // Heavy work #1 here.
ans := 15
myExecutor.Spawn("/", async.Do(func() {
myState.v1 = ans
myState.wg.Done()
}))
}()
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(500 * time.Millisecond) // Heavy work #2 here.
ans := 27
myExecutor.Spawn("/", async.Do(func() {
myState.v2 = ans
myState.wg.Done()
}))
}()
myExecutor.Spawn("/", myState.wg.Await().Then(async.Do(func() {
fmt.Println("v1 + v2 =", myState.v1+myState.v2)
})))
wg.Wait()
// Output:
// v1 + v2 = 42
}