考虑以下 C 代码片段:
int flag = 0;
/* Assume that the functions lock_helper, unlock_helper implement enter/leave in
* a global mutex and thread_start_helper simply runs the function in separate
* operating-system threads */
void worker1()
{
/* Long-running job here */
lock_helper();
if (!flag)
flag = 1;
unlock_helper();
}
void worker2()
{
/* Another long-running job here */
lock_helper();
if (!flag)
flag = 2;
unlock_helper();
}
int main(int argc, char **argv)
{
thread_start_helper(&worker1);
thread_start_helper(&worker2);
do
{
/* doing something */
} while (!flag);
/* do something with 'flag' */
}
问题:
主线程的'flag'是否可能永远为0(并且它 由于某些编译器优化而陷入 do/while 循环)?
'volatile' 修饰符会有什么不同吗?
如果答案是“取决于编译器提供的功能”,有没有 我可以使用配置脚本检查此“功能”的方式 编译时?
最佳答案
代码可能会按原样工作,但有些脆弱。一方面,这取决于对 flag
的读写在正在使用的处理器上是原子的(并且 flag
的对齐就足够了)。
我建议使用读锁来读取 flag
的值,或者使用您正在使用的任何线程库的功能来使 flag
正确地成为原子。
关于c - 在 C 程序中轮询其他线程写入的变量是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21217123/