c - 在 C 程序中轮询其他线程写入的变量是否安全?

标签 c multithreading thread-safety pthreads compiler-optimization

考虑以下 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/

相关文章:

c - 当 "aa"字符串分配给整数变量时发生了什么?

java - 如何在同一程序中多次创建线程的新实例

android - 无法在线程中定义适配器

Java线程-我想按顺序生成数字,例如: 1, 2,3,4...等等(只有2个线程)

java - 将synchronizedList与for循环结合使用并在其中添加项目

ios - 在嵌套 block 中保留对象的正确方法是什么

c - 使用netbeans c从txt文件读取文件地址

c - 如何像在 linux 内核中一样从头开始实现 container_of

c - 如何在 C 中分配 32 字节对齐的内存

检查线程是否未使用 C