-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexamples_test.go
66 lines (53 loc) · 1.32 KB
/
examples_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
62
63
64
65
66
package context_test
import (
"fmt"
"time"
context "github.com/mcfly722/context"
)
type node struct {
name string
}
func newNode(name string) *node {
return &node{name: name}
}
func (node *node) getName() string {
return node.name
}
// this method node should implement as Goroutine loop
func (node *node) Go(current context.Context) {
loop:
for {
select {
case _, isOpened := <-current.Context(): // this method returns context channel. If it closes, it means that we need to finish select loop
if !isOpened {
break loop
}
default: // you can use default or not, it works in both cases
{
}
}
}
fmt.Printf("4. context '%v' closed\n", node.getName())
}
func Example() {
rootContext := context.NewRootContext(newNode("root"))
child1Context, _ := rootContext.NewContextFor(newNode("child1"))
child2Context, _ := child1Context.NewContextFor(newNode("child2"))
child2Context.NewContextFor(newNode("child3"))
fmt.Printf("1. now waiting for 1 sec...\n")
go func() {
time.Sleep(1 * time.Second)
fmt.Printf("3. one second pass\n")
rootContext.Close()
}()
rootContext.Wait()
fmt.Printf("5. end\n")
// Output:
// 1. now waiting for 1 sec...
// 3. one second pass
// 4. context 'child3' closed
// 4. context 'child2' closed
// 4. context 'child1' closed
// 4. context 'root' closed
// 5. end
}