Search code examples
c++multithreadingatomiclock-free

Atomicity of IF and the following statement


This is A. Williams C++ Concurrency in Action book, lock-free stack with hazard pointers topic. Suppose I gain an understanding of it, except for just two lines, here they are (the source here):

// code before
if (old_head) {
res.swap(old_head->data);
// code after

The question is: can another thread delete (modify etc.) "old_head" pointer before it is dereferenced (old_head->data)? The logic says no cause the whole Williams' code is erroneous, but I doubt if it's a kind of an atomic operation. What do you think?


Solution

  • If old_head is available for multiple threads and quoted code block is not protected by any synchronization mechanism, then yes old_head could be modified between checking and dereferencing. if statement by itself does not guarantee any atomicity.