title: Why does a boolean need to be atomic?
body: <p>In rust, there is such a thing as an <a href="https://doc.rust-lang.org/std/sync/atomic/struct.AtomicBool.html" rel="nofollow noreferrer">AtomicBool</a>. It is defined as:</p>
  <blockquote>
  <p>A boolean type which can be safely shared between threads.</p>
  </blockquote>
  <p>I understand that if you're using a boolean to implement a thread lock, to be used from multiple threads to control access to a resource, doing something like:</p>
  <pre><code>// Acquire the lock
  if thread_lock == false:
      thread_lock = true
  
  ...
  
  // Release the lock
  thread_lock = false
  </code></pre>
  <p>Is definitely not thread safe. Both threads can read the thread_lock variable at the same time, see that it's unlocked (false), set it to true, and both think they have exclusive access to the thread.</p>
  <p>With a proper thread lock, you need a boolean where, when you try to set it, one of two things will happen:</p>
  <ul>
  <li>Trying to acquire a lock can fail if another thread already has a lock</li>
  <li>Trying to acquire a lock will block until no other threads have a lock</li>
  </ul>
  <p>I don't know if Rust has a concept like this, but I know Python's <code>threading.Lock</code> does exactly that.</p>
  <p>As far as I can tell, this is NOT the scenario that an <code>AtomicBool</code> addresses. An <code>AtomicBool</code> has a <code>load()</code> method, and a <code>store()</code> method. Neither return a <code>Result&lt;bool&gt;</code> type (implying the operation can't fail), and as far as I can tell, neither do any kind of blocking.</p>
  <p>What exactly does an <code>AtomicBool</code> protect us from? Why can we not use a regular bool from different threads (other than the fact that the compiler won't let us)?</p>
  <p>The only thing I can think of is that when one thread is writing the bits into memory, another might try to read those bits at the same time. A bool is 8 bits. If 4 of the 8 bits were written when the other thread tries to read the data, the data read will be 4 bits of the old value, and 4 bits of the new value. Is this the problem being addressed? Can this happen? It doesn't seem like even in that scenario, a bool would need to be atomic, since of the 8 bits, only one bit matters, which will either be a 0 or a 1.</p>