4

As far as I know they aren't.

Atomic objects are free of data races, yet they can still suffer from race conditions: two threads might start in an unpredictable order making the program outcome non-deterministic.

Shared data would be "safe" (protected by atomics) but the sequence or timing could still be wrong.

Can you confirm this?

Ignorant
  • 2,411
  • 4
  • 31
  • 48
  • 4
    Sure. You also need to know what terms like semaphore, mutex, monitor, reader/writer lock, condition variable, critical section, spinlock mean and when you use them. – Hans Passant Mar 02 '19 at 14:10

2 Answers2

1

Yes, you are correct that non-atomic operations may still have race condition. If you have non-atomic operations that depend on the state of the atomic object without interference from other threads, you need to use another synchronization technique to maintain consistency.

Atomic operations on the atomic object will be consistent, but not race-free. Non-atomic operations using the atomic object are not race-free.

mattm
  • 5,851
  • 11
  • 47
  • 77
  • 3
    Atomic operations are *not* automatically race-free. Threads A and B both do an atomic get-and-increment on an atomic counter. Which one gets the lower number? – Sneftel Mar 02 '19 at 18:06
1

Not just atomic objects, any primitive that can be used with operations performed by threads running concurrently:

  • mutex
  • condition variable
  • semaphore
  • barrier
  • atomic objects...

by definition are only useful if there is a race, an unpredictability in the access pattern. If the accesses where well ordered in a predictable way, you would have used a regular mutable object in the programming language.

But even if the order is a priori unknown, the end result can be deterministic: consider the concurrently running threads serving pages for a static Web server, with a count of pages and bytes served as the only mutable data structure. The statistics can be kept in a data structure protected by a mutex (a mutex isn't needed, it's just a simple example): the order of mutex locking is unpredictable, but the end result is that the data structure contains the sum of pages and bytes served; it doesn't matter in which order each thread adds the counts to the shared data.

curiousguy
  • 8,038
  • 2
  • 40
  • 58