-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoroutine.go
More file actions
52 lines (46 loc) · 1.05 KB
/
goroutine.go
File metadata and controls
52 lines (46 loc) · 1.05 KB
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
package chantrace
import (
"context"
"time"
)
// Go launches a traced goroutine. The child receives a context with its own
// goroutine ID (see [GoID]), and its parent ID is recorded for spawn trees.
func Go(ctx context.Context, label string, fn func(ctx context.Context)) {
if !enabled.Load() {
go fn(ctx)
return
}
parentGID := currentRuntimeGID()
if parentGID == 0 {
parentGID = GoID(ctx)
}
pc := maybeCapturePC()
childTraceID := nextGoroutineID()
childCtx := context.WithValue(ctx, goidKey, childTraceID)
go func() {
childGID := currentRuntimeGID()
if childGID == 0 {
childGID = childTraceID
}
defaultCollector.emit(Event{
Kind: GoSpawn,
Timestamp: time.Now().UnixNano(),
GoroutineID: childGID,
ParentGID: parentGID,
GoLabel: label,
PC: pc,
})
defer func() {
if enabled.Load() {
defaultCollector.emit(Event{
Kind: GoExit,
Timestamp: time.Now().UnixNano(),
GoroutineID: childGID,
GoLabel: label,
PC: pc,
})
}
}()
fn(childCtx)
}()
}