DEV Community

ynwd
ynwd

Posted on

Data Races di Golang

Data race adalah kondisi ketika sebuah variable diakses oleh dua go routine yang berjalan secara bersamaan (concurrent).

Mari kita lihat contohnya.
code

Source code: https://play.golang.org/p/4uWsRaxBs79

Jika kode diatas kita jalankan secara biasa, hasilnya "hi". Seolah-olah tidak terjadi masalah.

$ go run main.go
hi  
Enter fullscreen mode Exit fullscreen mode

Diagram data races

Lalu, bagaimana cara melakukan simulasi agar terjadi race condition?

Simulasi data race

Untungnya, go sudah menyediakan cara agar kita melakukan simulasi data race.

Jalankan program dengan -race

$ go run -race main.go
Enter fullscreen mode Exit fullscreen mode

Hasilnya:

hi
==================
WARNING: DATA RACE
Write at 0x00c000118210 by goroutine 7:
  main.getText.func1()
      /Users/pro/Documents/apps/cms/cmd/main.go:9 +0x30

Previous read at 0x00c000118210 by main goroutine:
  main.getText()
      /Users/pro/Documents/apps/cms/cmd/main.go:12 +0xda
  main.main()
      /Users/pro/Documents/apps/cms/cmd/main.go:17 +0x24

Goroutine 7 (running) created at:
  main.getText()
      /Users/pro/Documents/apps/cms/cmd/main.go:8 +0xd0
  main.main()
      /Users/pro/Documents/apps/cms/cmd/main.go:17 +0x24
==================
Found 1 data race(s)
exit status 66
Enter fullscreen mode Exit fullscreen mode

Pembahasan error

Mari kita bahas satu persatu

Blok #1

WARNING: DATA RACE
Write at 0x00c000118210 by goroutine 7:
  main.getText.func1()
      /Users/pro/Documents/apps/cms/cmd/main.go:9 +0x30
Enter fullscreen mode Exit fullscreen mode

Menjelaskan di mana data race terjadi: line ke-9.

Blok #2

Previous read at 0x00c000118210 by main goroutine:
  main.getText()
      /Users/pro/Documents/apps/cms/cmd/main.go:12 +0xda
  main.main()
      /Users/pro/Documents/apps/cms/cmd/main.go:17 +0x24
Enter fullscreen mode Exit fullscreen mode

Menjelaskan di mana variable tersebut sudah terpanggil: line ke-12.

Blok #3

Goroutine 7 (running) created at:
  main.getText()
      /Users/pro/Documents/apps/cms/cmd/main.go:8 +0xd0
  main.main()
      /Users/pro/Documents/apps/cms/cmd/main.go:17 +0x24
Enter fullscreen mode Exit fullscreen mode

Menjelaskan di mana go routine tersebut dibuat: line ke-8.

Top comments (0)