1

Should I always care about atomicity when assigning values in multi-threaded projects? I have two threads running parallel. Can I safely change non-DWORD variable if it is used as flag only? Or do I have to use DWORD aligned variable (or DWORD itself) since Microsoft guarantees that it will be changed atomically? Or do I have to slow down my code and use Interlocked*() functions instead? Will my code still work fine if I go down from 32- to 16-bits system or go up from 32- to 64-bits system?

/* real value doesn't matter, only null or not-null */
short flag;
// DWORD flag;

DWORD WINAPI thread_1(LPVOID* param)
{
  while(true){/* do stuff, flag can be changed non-atomically */}
  return 0;
}

DWORD WINAPI thread_2(LPVOID* param)
{
  while(true){if(flag){/* do stuff */}}
  return 0;
}

update

thread_2 is only observing the flag while thread_1 changes it.

Ivars
  • 2,375
  • 7
  • 22
  • 31

1 Answers1

1

You have to use use the Interlocked* functions or (better yet) C++11 atomics.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
  • thanks. i made a little update. do i still have to use locks if only one of two threads changes variable while other observes? – Ivars Jan 09 '14 at 15:10
  • 1
    Yes. Anytime you have a write concurrent with anything, you need atomics. (Or use locks to make it not concurrent.) – Sebastian Redl Jan 09 '14 at 15:12
  • what would be better to use: microsoft interlocked functions or c++11 atomics? – Ivars Jan 09 '14 at 15:14
  • 1
    Atomics. They have more clearly defined semantics, making them easier to reason about for both programmers and compilers (which is good for optimization). They're also portable, which may matter to you in the future. – Sebastian Redl Jan 09 '14 at 15:20