-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.go
56 lines (44 loc) · 944 Bytes
/
main.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
package main
import (
"context"
"fmt"
"time"
)
type data struct {
result string
}
func main() {
// set deadline for goroutine to return computational result.
deadline := time.Now().Add(5 * time.Millisecond)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
compute := func() <-chan data {
ch := make(chan data)
go func() {
defer close(ch)
deadline, ok := ctx.Deadline()
if ok {
if deadline.Sub(time.Now().Add(50*time.Millisecond)) < 0 {
fmt.Println("not sufficient time given, terminating")
return
}
}
// Simulate work.
time.Sleep(50 * time.Millisecond)
// Report result.
select {
case ch <- data{"123"}:
case <-ctx.Done():
fmt.Println("work cancelled")
return
}
}()
return ch
}
// Wait for the work to finish. If it takes too long move on.
ch := compute()
d, ok := <-ch
if ok {
fmt.Println("work complete", d)
}
}