- The Go Programming Language (original) (raw)
Source file src/time/sleep.go
1
2
3
4
5 package time
6
7 import (
8 "internal/godebug"
9 "unsafe"
10 )
11
12
13
14 func Sleep(d Duration)
15
16 var asynctimerchan = godebug.New("asynctimerchan")
17
18
19
20
21
22 func syncTimer(c chan Time) unsafe.Pointer {
23
24
25 if asynctimerchan.Value() == "1" {
26 asynctimerchan.IncNonDefault()
27 return nil
28 }
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 return *(*unsafe.Pointer)(unsafe.Pointer(&c))
46 }
47
48
49
50
51
52 func when(d Duration) int64 {
53 if d <= 0 {
54 return runtimeNano()
55 }
56 t := runtimeNano() + int64(d)
57 if t < 0 {
58
59
60 t = 1<<63 - 1
61 }
62 return t
63 }
64
65
66
67
68
69
70
71
72 func newTimer(when, period int64, f func(any, uintptr, int64), arg any, cp unsafe.Pointer) *Timer
73
74
75 func stopTimer(*Timer) bool
76
77
78 func resetTimer(t *Timer, when, period int64) bool
79
80
81
82
83
84
85
86
87
88
89 type Timer struct {
90 C <-chan Time
91 initTimer bool
92 }
93
94
95
96
97
98
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 func (t *Timer) Stop() bool { 114 if !t.initTimer { 115 panic("time: Stop called on uninitialized Timer") 116 } 117 return stopTimer(t) 118 } 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 func NewTimer(d Duration) *Timer { 144 c := make(chan Time, 1) 145 t := (*Timer)(newTimer(when(d), 0, sendTime, c, syncTimer(c))) 146 t.C = c 147 return t 148 } 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 func (t *Timer) Reset(d Duration) bool { 172 if !t.initTimer { 173 panic("time: Reset called on uninitialized Timer") 174 } 175 w := when(d) 176 return resetTimer(t, w, 0) 177 } 178 179 180 func sendTime(c any, seq uintptr, delta int64) { 181 182 183 184 185 186 select { 187 case c.(chan Time) <- Now().Add(Duration(-delta)): 188 default: 189 } 190 } 191 192 193 194 195 196 197 198 199 200 201 202 func After(d Duration) <-chan Time { 203 return NewTimer(d).C 204 } 205 206 207 208 209 210 func AfterFunc(d Duration, f func()) *Timer { 211 return (*Timer)(newTimer(when(d), 0, goFunc, f, nil)) 212 } 213 214 func goFunc(arg any, seq uintptr, delta int64) { 215 go arg.(func())() 216 } 217