Does this code safe?

99 views
Skip to first unread message

Cholerae Hu

unread,
Jul 5, 2019, 10:53:05 AM7/5/19
to golang-nuts
package main

import (
"sync/atomic"
"sync"
)

func main() {
var n int32
var m sync.Mutex
var wg sync.WaitGroup
wg.Add(2)
go func() {
for {
atomic.LoadInt32(&n)
}
wg.Done()
}()
go func() {
for {
m.Lock()
n = 1
m.Unlock()
}
wg.Done()
}()
wg.Wait()
}

Does it safe to use atomic read an int and write an int non-atomically but in lock concurrently? Race detector will report it data race.

Steven Hartland

unread,
Jul 5, 2019, 11:03:23 AM7/5/19
to Cholerae Hu, golang-nuts
Use the same method for both Load and Set, also your example will never complete as your for loops will run forever.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/825f9031-74b9-41b6-87af-dccfa7d98d04%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Michael Jones

unread,
Jul 5, 2019, 11:12:34 AM7/5/19
to Cholerae Hu, golang-nuts
The race detector detects races, like smoke detectors detect smoke and water detectors detect water. Are you asking if the race detector is broken? If its judgement is just a guess? Not a guess. A scientific observation. Your code is not safe. 

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/825f9031-74b9-41b6-87af-dccfa7d98d04%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
Michael T. Jones
michae...@gmail.com

Robert Johnstone

unread,
Jul 5, 2019, 1:54:21 PM7/5/19
to golang-nuts
In theory, the non-atomic store could tear with respect to the atomic load.
Reply all
Reply to author
Forward
0 new messages