-
Notifications
You must be signed in to change notification settings - Fork 44
/
concurrent.go
122 lines (90 loc) · 2.36 KB
/
concurrent.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"context"
"log"
"os"
"os/signal"
"time"
"github.com/cschleiden/go-workflows/backend"
"github.com/cschleiden/go-workflows/client"
"github.com/cschleiden/go-workflows/samples"
"github.com/cschleiden/go-workflows/worker"
"github.com/cschleiden/go-workflows/workflow"
"github.com/google/uuid"
)
func main() {
ctx := context.Background()
b := samples.GetBackend("concurrent")
// Run worker
go RunWorker(ctx, b)
// Start workflow via client
c := client.New(b)
startWorkflow(ctx, c)
c2 := make(chan os.Signal, 1)
signal.Notify(c2, os.Interrupt)
<-c2
}
func startWorkflow(ctx context.Context, c *client.Client) {
wf, err := c.CreateWorkflowInstance(ctx, client.WorkflowInstanceOptions{
InstanceID: uuid.NewString(),
}, Workflow1, "Hello world")
if err != nil {
panic("could not start workflow")
}
log.Println("Started workflow", wf.InstanceID)
}
func RunWorker(ctx context.Context, mb backend.Backend) {
w := worker.New(mb, nil)
w.RegisterWorkflow(Workflow1)
w.RegisterActivity(Activity1)
w.RegisterActivity(Activity2)
if err := w.Start(ctx); err != nil {
panic("could not start worker")
}
}
func Workflow1(ctx workflow.Context, msg string) (string, error) {
logger := workflow.Logger(ctx)
logger.Debug("Entering Workflow1")
logger.Debug("\tWorkflow instance input:", "msg", msg)
defer func() {
logger.Debug("Leaving Workflow1")
}()
wg := workflow.NewWaitGroup()
wg.Add(2)
workflow.Go(ctx, func(ctx workflow.Context) {
defer wg.Done()
a1 := workflow.ExecuteActivity[int](ctx, workflow.DefaultActivityOptions, Activity1, 35, 12)
r, err := a1.Get(ctx)
if err != nil {
panic(err)
}
logger.Debug("A1 result", "r", r)
})
workflow.Go(ctx, func(ctx workflow.Context) {
defer wg.Done()
a2 := workflow.ExecuteActivity[int](ctx, workflow.DefaultActivityOptions, Activity2)
r, err := a2.Get(ctx)
if err != nil {
panic(err)
}
logger.Debug("A2 result", "r", r)
})
// Wait for both "Go"-routines to finish
wg.Wait(ctx)
return "result", nil
}
func Activity1(ctx context.Context, a, b int) (int, error) {
log.Println("Entering Activity1")
defer func() {
log.Println("Leaving Activity1")
}()
return a + b, nil
}
func Activity2(ctx context.Context) (int, error) {
log.Println("Entering Activity2")
time.Sleep(5 * time.Second)
defer func() {
log.Println("Leaving Activity2")
}()
return 12, nil
}