ynwd
Posted on November 10, 2021
Data race adalah kondisi ketika sebuah variable diakses oleh dua go routine yang berjalan secara bersamaan (concurrent).
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
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
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
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
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
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
Menjelaskan di mana go routine tersebut dibuat: line ke-8.
Posted on November 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.