-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaitgroup_example_test.go
More file actions
51 lines (39 loc) · 915 Bytes
/
waitgroup_example_test.go
File metadata and controls
51 lines (39 loc) · 915 Bytes
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
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.Go(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.Go(func() {
time.Sleep(500 * time.Millisecond) // Heavy work #1 here.
ans := 15
myExecutor.Spawn(async.Do(func() {
myState.v1 = ans
myState.wg.Done()
}))
})
wg.Go(func() {
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
}