The type does not need to be Int32 because the Compare-and-Swap operation works on int32. It is fine as is.
The compare-and-swap operation provided by the hardware guarantees that the compare-and-swap operation is atomic, which means no other read operation by any other goroutine will see the value of the state field while the compare-and-swap is in progress. Any other read will read it only before or after any compare-and-swap, never in-between. Therefore, the lines reading the state prior to the line with the compare-and-swap are fine. Those lines are an optimization to avoid the more expensive compare-and-swap that follows. The code will first check if the lock is available and then try to obtain the lock. The check for availability does not use any atomic or locking, it is just a pre-check for the following lines that do use the required atomic operation. On Thu, Aug 25, 2022 at 10:16 AM smal...@gmail.com <smalln...@gmail.com> wrote: > Mutex.TryLock is implemented as the below. > The second line is fetching value of the state but it does not use atomic. > Is it is a race issue? > > Should type of the state be changed to atomic.Int32 just like Waitgroup? > > > func (m *Mutex) TryLock() bool { > > old := m.state > > if old&(mutexLocked|mutexStarving) != 0 { > > return false > > } > > if !atomic.CompareAndSwapInt32(&m.state, old, old|mutexLocked) { > > return false > > } > > > > if race.Enabled { > > race.Acquire(unsafe.Pointer(m)) > > } > > return true > > } > > -- > 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+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/c076387c-aef7-4960-afc1-dbe67ed4fa48n%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/c076387c-aef7-4960-afc1-dbe67ed4fa48n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- 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+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAKL%3DS7EN6fQ%3DhpYeEq-Lng-E_uCWR7AwKTD85OjurhtGiCanxQ%40mail.gmail.com.