/
two_buyer.go
109 lines (103 loc) · 2.08 KB
/
two_buyer.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
package twobuyer
import (
"context"
"fmt"
"go.opentelemetry.io/otel/api/global"
"go.opentelemetry.io/otel/api/trace"
"math/rand"
"sync"
)
func (a *A) run(wg *sync.WaitGroup) {
defer wg.Done()
ctx := context.Background()
var span trace.Span
ctx, span = a.tracer.Start(ctx, "TwoBuyer Endpoint A")
defer span.End()
// Send query to S
var query = rand.Intn(100)
fmt.Println("A: Sending query", query)
a.SendS(ctx, "query", query)
// Receive a quote
var quote = a.RecvS(ctx, "quote")
var otherShare = a.RecvB(ctx, "share")
if otherShare*2 >= quote {
// 1 stands for ok
a.SendS(ctx, "buy", 1)
} else {
a.SendS(ctx, "buy", 0)
}
}
func (s *S) run(wg *sync.WaitGroup) {
defer wg.Done()
ctx := context.Background()
var span trace.Span
ctx, span = s.tracer.Start(ctx, "TwoBuyer Endpoint S")
defer span.End()
// Receive a query
var query = s.RecvA(ctx, "query")
// Send a quote
var quote = query * 2
fmt.Println("S: Sending quote", quote)
s.SendA(ctx, "quote", quote)
s.SendB(ctx, "quote", quote)
var decision = s.RecvA(ctx, "buy")
if decision == 1 {
fmt.Println("Succeed!")
} else {
fmt.Println("Failed to succeed!")
}
}
func (b *B) run(wg *sync.WaitGroup) {
defer wg.Done()
ctx := context.Background()
var span trace.Span
ctx, span = b.tracer.Start(ctx, "TwoBuyer Endpoint B")
defer span.End()
// Receive a quote
var quote = b.RecvS(ctx, "quote")
// Propose a share
var share = quote/2 + rand.Intn(10) - 5
fmt.Println("B: Proposing share", share)
b.SendA(ctx, "share", share)
}
func spawn() (*A, *B, *S) {
var a = A{
make(chan int, 1),
make(chan int, 1),
nil,
nil,
global.Tracer("TwoBuyer/A"),
}
var s = S{
make(chan int, 1),
make(chan int, 1),
nil,
nil,
global.Tracer("TwoBuyer/S"),
}
var b = B{
make(chan int, 1),
make(chan int, 1),
nil,
nil,
global.Tracer("TwoBuyer/B"),
}
s.a = &a
b.a = &a
a.s = &s
b.s = &s
a.b = &b
s.b = &b
return &a, &b, &s
}
func RunAll() {
shutdown := InitOtlpTracer()
defer shutdown()
var wg sync.WaitGroup
var a, b, s = spawn()
wg.Add(3)
go a.run(&wg)
go b.run(&wg)
go s.run(&wg)
wg.Wait()
}