race_detector.html 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <!--{
  2. "Title": "Data Race Detector",
  3. "Template": true
  4. }-->
  5. <h2 id="Introduction">Introduction</h2>
  6. <p>
  7. Data races are among the most common and hardest to debug types of bugs in concurrent systems.
  8. A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write.
  9. See the <a href="/ref/mem/">The Go Memory Model</a> for details.
  10. </p>
  11. <p>
  12. Here is an example of a data race that can lead to crashes and memory corruption:
  13. </p>
  14. <pre>
  15. func main() {
  16. c := make(chan bool)
  17. m := make(map[string]string)
  18. go func() {
  19. m["1"] = "a" // First conflicting access.
  20. c &lt;- true
  21. }()
  22. m["2"] = "b" // Second conflicting access.
  23. &lt;-c
  24. for k, v := range m {
  25. fmt.Println(k, v)
  26. }
  27. }
  28. </pre>
  29. <h2 id="Usage">Usage</h2>
  30. <p>
  31. To help diagnose such bugs, Go includes a built-in data race detector.
  32. To use it, add the <code>-race</code> flag to the go command:
  33. </p>
  34. <pre>
  35. $ go test -race mypkg // to test the package
  36. $ go run -race mysrc.go // to run the source file
  37. $ go build -race mycmd // to build the command
  38. $ go install -race mypkg // to install the package
  39. </pre>
  40. <h2 id="Report_Format">Report Format</h2>
  41. <p>
  42. When the race detector finds a data race in the program, it prints a report.
  43. The report contains stack traces for conflicting accesses, as well as stacks where the involved goroutines were created.
  44. Here is an example:
  45. </p>
  46. <pre>
  47. WARNING: DATA RACE
  48. Read by goroutine 185:
  49. net.(*pollServer).AddFD()
  50. src/net/fd_unix.go:89 +0x398
  51. net.(*pollServer).WaitWrite()
  52. src/net/fd_unix.go:247 +0x45
  53. net.(*netFD).Write()
  54. src/net/fd_unix.go:540 +0x4d4
  55. net.(*conn).Write()
  56. src/net/net.go:129 +0x101
  57. net.func·060()
  58. src/net/timeout_test.go:603 +0xaf
  59. Previous write by goroutine 184:
  60. net.setWriteDeadline()
  61. src/net/sockopt_posix.go:135 +0xdf
  62. net.setDeadline()
  63. src/net/sockopt_posix.go:144 +0x9c
  64. net.(*conn).SetDeadline()
  65. src/net/net.go:161 +0xe3
  66. net.func·061()
  67. src/net/timeout_test.go:616 +0x3ed
  68. Goroutine 185 (running) created at:
  69. net.func·061()
  70. src/net/timeout_test.go:609 +0x288
  71. Goroutine 184 (running) created at:
  72. net.TestProlongTimeout()
  73. src/net/timeout_test.go:618 +0x298
  74. testing.tRunner()
  75. src/testing/testing.go:301 +0xe8
  76. </pre>
  77. <h2 id="Options">Options</h2>
  78. <p>
  79. The <code>GORACE</code> environment variable sets race detector options.
  80. The format is:
  81. </p>
  82. <pre>
  83. GORACE="option1=val1 option2=val2"
  84. </pre>
  85. <p>
  86. The options are:
  87. </p>
  88. <ul>
  89. <li>
  90. <code>log_path</code> (default <code>stderr</code>): The race detector writes
  91. its report to a file named <code>log_path.<em>pid</em></code>.
  92. The special names <code>stdout</code>
  93. and <code>stderr</code> cause reports to be written to standard output and
  94. standard error, respectively.
  95. </li>
  96. <li>
  97. <code>exitcode</code> (default <code>66</code>): The exit status to use when
  98. exiting after a detected race.
  99. </li>
  100. <li>
  101. <code>strip_path_prefix</code> (default <code>""</code>): Strip this prefix
  102. from all reported file paths, to make reports more concise.
  103. </li>
  104. <li>
  105. <code>history_size</code> (default <code>1</code>): The per-goroutine memory
  106. access history is <code>32K * 2**history_size elements</code>.
  107. Increasing this value can avoid a "failed to restore the stack" error in reports, at the
  108. cost of increased memory usage.
  109. </li>
  110. <li>
  111. <code>halt_on_error</code> (default <code>0</code>): Controls whether the program
  112. exits after reporting first data race.
  113. </li>
  114. </ul>
  115. <p>
  116. Example:
  117. </p>
  118. <pre>
  119. $ GORACE="log_path=/tmp/race/report strip_path_prefix=/my/go/sources/" go test -race
  120. </pre>
  121. <h2 id="Excluding_Tests">Excluding Tests</h2>
  122. <p>
  123. When you build with <code>-race</code> flag, the <code>go</code> command defines additional
  124. <a href="/pkg/go/build/#hdr-Build_Constraints">build tag</a> <code>race</code>.
  125. You can use the tag to exclude some code and tests when running the race detector.
  126. Some examples:
  127. </p>
  128. <pre>
  129. // +build !race
  130. package foo
  131. // The test contains a data race. See issue 123.
  132. func TestFoo(t *testing.T) {
  133. // ...
  134. }
  135. // The test fails under the race detector due to timeouts.
  136. func TestBar(t *testing.T) {
  137. // ...
  138. }
  139. // The test takes too long under the race detector.
  140. func TestBaz(t *testing.T) {
  141. // ...
  142. }
  143. </pre>
  144. <h2 id="How_To_Use">How To Use</h2>
  145. <p>
  146. To start, run your tests using the race detector (<code>go test -race</code>).
  147. The race detector only finds races that happen at runtime, so it can't find
  148. races in code paths that are not executed.
  149. If your tests have incomplete coverage,
  150. you may find more races by running a binary built with <code>-race</code> under a realistic
  151. workload.
  152. </p>
  153. <h2 id="Typical_Data_Races">Typical Data Races</h2>
  154. <p>
  155. Here are some typical data races. All of them can be detected with the race detector.
  156. </p>
  157. <h3 id="Race_on_loop_counter">Race on loop counter</h3>
  158. <pre>
  159. func main() {
  160. var wg sync.WaitGroup
  161. wg.Add(5)
  162. for i := 0; i < 5; i++ {
  163. go func() {
  164. fmt.Println(i) // Not the 'i' you are looking for.
  165. wg.Done()
  166. }()
  167. }
  168. wg.Wait()
  169. }
  170. </pre>
  171. <p>
  172. The variable <code>i</code> in the function literal is the same variable used by the loop, so
  173. the read in the goroutine races with the loop increment.
  174. (This program typically prints 55555, not 01234.)
  175. The program can be fixed by making a copy of the variable:
  176. </p>
  177. <pre>
  178. func main() {
  179. var wg sync.WaitGroup
  180. wg.Add(5)
  181. for i := 0; i < 5; i++ {
  182. go func(j int) {
  183. fmt.Println(j) // Good. Read local copy of the loop counter.
  184. wg.Done()
  185. }(i)
  186. }
  187. wg.Wait()
  188. }
  189. </pre>
  190. <h3 id="Accidentally_shared_variable">Accidentally shared variable</h3>
  191. <pre>
  192. // ParallelWrite writes data to file1 and file2, returns the errors.
  193. func ParallelWrite(data []byte) chan error {
  194. res := make(chan error, 2)
  195. f1, err := os.Create("file1")
  196. if err != nil {
  197. res &lt;- err
  198. } else {
  199. go func() {
  200. // This err is shared with the main goroutine,
  201. // so the write races with the write below.
  202. _, err = f1.Write(data)
  203. res &lt;- err
  204. f1.Close()
  205. }()
  206. }
  207. f2, err := os.Create("file2") // The second conflicting write to err.
  208. if err != nil {
  209. res &lt;- err
  210. } else {
  211. go func() {
  212. _, err = f2.Write(data)
  213. res &lt;- err
  214. f2.Close()
  215. }()
  216. }
  217. return res
  218. }
  219. </pre>
  220. <p>
  221. The fix is to introduce new variables in the goroutines (note the use of <code>:=</code>):
  222. </p>
  223. <pre>
  224. ...
  225. _, err := f1.Write(data)
  226. ...
  227. _, err := f2.Write(data)
  228. ...
  229. </pre>
  230. <h3 id="Unprotected_global_variable">Unprotected global variable</h3>
  231. <p>
  232. If the following code is called from several goroutines, it leads to races on the <code>service</code> map.
  233. Concurrent reads and writes of the same map are not safe:
  234. </p>
  235. <pre>
  236. var service map[string]net.Addr
  237. func RegisterService(name string, addr net.Addr) {
  238. service[name] = addr
  239. }
  240. func LookupService(name string) net.Addr {
  241. return service[name]
  242. }
  243. </pre>
  244. <p>
  245. To make the code safe, protect the accesses with a mutex:
  246. </p>
  247. <pre>
  248. var (
  249. service map[string]net.Addr
  250. serviceMu sync.Mutex
  251. )
  252. func RegisterService(name string, addr net.Addr) {
  253. serviceMu.Lock()
  254. defer serviceMu.Unlock()
  255. service[name] = addr
  256. }
  257. func LookupService(name string) net.Addr {
  258. serviceMu.Lock()
  259. defer serviceMu.Unlock()
  260. return service[name]
  261. }
  262. </pre>
  263. <h3 id="Primitive_unprotected_variable">Primitive unprotected variable</h3>
  264. <p>
  265. Data races can happen on variables of primitive types as well (<code>bool</code>, <code>int</code>, <code>int64</code>, etc.),
  266. as in this example:
  267. </p>
  268. <pre>
  269. type Watchdog struct{ last int64 }
  270. func (w *Watchdog) KeepAlive() {
  271. w.last = time.Now().UnixNano() // First conflicting access.
  272. }
  273. func (w *Watchdog) Start() {
  274. go func() {
  275. for {
  276. time.Sleep(time.Second)
  277. // Second conflicting access.
  278. if w.last < time.Now().Add(-10*time.Second).UnixNano() {
  279. fmt.Println("No keepalives for 10 seconds. Dying.")
  280. os.Exit(1)
  281. }
  282. }
  283. }()
  284. }
  285. </pre>
  286. <p>
  287. Even such "innocent" data races can lead to hard-to-debug problems caused by
  288. non-atomicity of the memory accesses,
  289. interference with compiler optimizations,
  290. or reordering issues accessing processor memory .
  291. </p>
  292. <p>
  293. A typical fix for this race is to use a channel or a mutex.
  294. To preserve the lock-free behavior, one can also use the
  295. <a href="/pkg/sync/atomic/"><code>sync/atomic</code></a> package.
  296. </p>
  297. <pre>
  298. type Watchdog struct{ last int64 }
  299. func (w *Watchdog) KeepAlive() {
  300. atomic.StoreInt64(&amp;w.last, time.Now().UnixNano())
  301. }
  302. func (w *Watchdog) Start() {
  303. go func() {
  304. for {
  305. time.Sleep(time.Second)
  306. if atomic.LoadInt64(&amp;w.last) < time.Now().Add(-10*time.Second).UnixNano() {
  307. fmt.Println("No keepalives for 10 seconds. Dying.")
  308. os.Exit(1)
  309. }
  310. }
  311. }()
  312. }
  313. </pre>
  314. <h2 id="Supported_Systems">Supported Systems</h2>
  315. <p>
  316. The race detector runs on <code>darwin/amd64</code>, <code>freebsd/amd64</code>,
  317. <code>linux/amd64</code>, and <code>windows/amd64</code>.
  318. </p>
  319. <h2 id="Runtime_Overheads">Runtime Overhead</h2>
  320. <p>
  321. The cost of race detection varies by program, but for a typical program, memory
  322. usage may increase by 5-10x and execution time by 2-20x.
  323. </p>