[英]Non-atomical assignement in multi-threaded applications
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?
如果非DWORD变量仅用作标志,可以安全地更改它吗? Or do I have to use DWORD aligned variable (or DWORD itself) since Microsoft guarantees that it will be changed atomically?
还是我必须使用DWORD对齐变量(或DWORD本身),因为Microsoft保证将对其进行原子更改? Or do I have to slow down my code and use Interlocked*() functions instead?
还是我必须放慢我的代码并改用Interlocked *()函数? 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?
如果我从32位系统降到16位系统或从32位系统升到64位系统,我的代码是否仍能正常工作?
/* 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. thread_2
仅在thread_1
更改时观察该标志。
您必须使用Interlocked*
函数或(更好)的C ++ 11原子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.