2

Isn't it thread safe when only write and read int in critical section between threads? So What is the difference between atomic_int and int? Is 'int' not atomically?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
f1msch
  • 509
  • 2
  • 12
  • Also related: [Why is integer assignment on a naturally aligned variable atomic on x86?](https://stackoverflow.com/a/36685056). And another close duplicate: [Difference between atomic and int](https://stackoverflow.com/q/64506385) which should have come up in your searches. – Peter Cordes Jun 14 '22 at 08:47
  • 1
    If you only read/write something in a critical section, it doesn't need to be atomic. You have mutual exclusion from locking, so it doesn't matter how many temporary steps are visible. – Peter Cordes Jun 14 '22 at 08:48
  • Also related, or a good duplicate: [What exactly is std::atomic?](https://stackoverflow.com/q/31978324) – Peter Cordes Jun 14 '22 at 08:55
  • 1
    In addition to _atomicity_, atomic types also allow you to control the _ordering of memory operations_, which may be of vital importance. For instance, even though writing to aligned `int` with `mov` instruction is atomic on x64, with `atomic_int`, compilers typically generate `xchg` thanks to the default sequential consistency ordering requirements. Live demo: https://godbolt.org/z/joGaozPE7. – Daniel Langr Jun 14 '22 at 09:23
  • "_Is 'int' not atomically?_": `std::atomic` (and `std::atomic_*` types) are the only atomic types. No other type is atomic. But the linked duplicates explain that in much more detail. – user17732522 Jun 15 '22 at 03:37

1 Answers1

2

A std::atomic_int is guaranteed by the standard not to have data races, at all. You don't need to protect it with critical sections.

If you wouldn't have a data race with int (such as in a critical section, with a lock that all accesses to the variable respect), then you redundantly wouldn't with std::atomic_int either.

You only need std::atomic<T> if you want to access a shared variable without mutexes or other synchronization to that gives 1 thread at a time exclusive ownership of it.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Caleth
  • 52,200
  • 2
  • 44
  • 75
  • But write/read `int` with no lock isn't atomic itself? If no consider of memory sequence or `i++` problems. – f1msch Jun 15 '22 at 03:16