c++ - possible concurrent write of *same* value to an integer. Do I need an atomic variable? -
i want introduce optimization legacy code. optimization boils down following simple example:
class foo{ static int m_count; // allocated , initialized -1 indicate it's uninitialized. void fun(){ if (m_count ==-1) m_count = execute_db_call(); // return val > 0. if (m_count == 1) { // call special == 1 optimized code. } else { // call expensive code. } } }
fun()
called millions of times on hundreds of threads, running concurrently on 256 core server.execute_db_call
expensive, , return value constant lifetime of application.
do need or want make m_count
atomic? in worst case multiple threads might call execute_db_call
, , same value, , write value same location in memory. race condition when both threads attempt write same integer value?
if did make member atomic, kind of performance overhead looking @ subsequent read behavior?
per standard §1.10/21:
the execution of program contains data race if contains 2 conflicting actions in different threads, @ least 1 of not atomic, , neither happens before other. such data race results in undefined behavior.
it looks code matches definition, ub. now, assuming application never crush (oh well...) might unnecessary execute_db_call
calls, , have explicitly stated "execute_db_call expensive", it's still bad.
Comments
Post a Comment