You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: README.md
+35-2
Original file line number
Diff line number
Diff line change
@@ -1,8 +1,13 @@
1
1
# Notes: Golang Advanced Concurrency Concepts
2
2
3
3
The tutorial consist of the following modules (in sense of Go Modules):
4
-
*`context/server`
5
-
*`context/cancellation`
4
+
*`context/cancel1`
5
+
*`context/cancel2`
6
+
*`context/cancel3`
7
+
*`context/emit`
8
+
*`context/listen`
9
+
*`context/timeout`
10
+
*`context/value`
6
11
*`error_group`
7
12
*`errors_in_waitgroup`
8
13
*`gosched`
@@ -23,6 +28,34 @@ There are two sides to the context cancellation, that can be implemented:
23
28
* Listening for the cancellation event,
24
29
* Emitting the cancellation event.
25
30
31
+
Things to remember about `context`:
32
+
* A `context` object can be cancelled only once
33
+
* Use it when you want to actually cancell an operation, not when you want to propagate errors
34
+
* Wrapping a cancellable context with `WithTimeout` or other functions make the context object cancellable in too many ways.
35
+
* Pass a child context to a goroutine you start or pass an independent context object. Here is an example:
36
+
```
37
+
func parent(rootCtx context.Context) {
38
+
ctx, cancel := context.WithCancel(rootCtx)
39
+
defer cancel()
40
+
41
+
someArg := "loremipsum"
42
+
go child(context.Background(), someArg)
43
+
}
44
+
```
45
+
Note: calling `cancel()` in the parent goroutine may cancel the child goroutine because there is no synchronization of the child - `parent()` (and thus its `defer`) does not wait for `child()`.
46
+
* do not pass the `cancel()` function downstream. It will result in the invoker of the cancellation function not knowning what the upstream impact of cancelling the context may be eg. there may be other contexts that are derived from the cancelled context.
47
+
48
+
49
+
Context factory methods:
50
+
* for a parent/new context: `Background()`
51
+
* for a cancellation context: `WithCancel()`
52
+
* for a time-limited context: `WithTimeout()`, `WithDeadline()`
53
+
* for a key-value storing context: `WithValue()`
54
+
* for an empty context:`TODO()`.
55
+
56
+
How to accept/use `context` objects in downstream:
57
+
58
+
26
59
27
60
### `context/listen`
28
61
In this example an HTTP server on port 9000 is set up. It processes a request within 2 seconds.
0 commit comments