You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中用while循环配合锁变量避免竞态条件为何无效?

手动自旋锁实现的竞态问题
#include <stdio.h>
#include <pthread.h>

long mails = 0;
int lock = 0;

void *routine()
{
  printf("Thread Start\n");
  for (long i = 0; i < 100000; i++)
  {
    while (lock)
    {
    }

    lock = 1;
    mails++;
    lock = 0;
  }
  printf("Thread End\n");
}

int main(int argc, int *argv[])
{
  pthread_t p1, p2;
  if (pthread_create(&p1, NULL, &routine, NULL) != 0)
  {
    return 1;
  }
  if (pthread_create(&p2, NULL, &routine, NULL) != 0)
  {
    return 2;
  }
  if (pthread_join(p1, NULL) != 0)
  {
    return 3;
  }
  if (pthread_join(p2, NULL) != 0)
  {
    return 4;
  }
  printf("Number of mails: %ld \n", mails);
  return 0;
}
  • 代码中两个线程各自通过for循环对mails变量累加100000次,理论上最终结果应为200000。
  • 为避免竞态条件,代码尝试用lock变量配合while循环实现自旋锁逻辑:先检查lock是否为0,若为1则循环等待;拿到锁后执行mails++,最后释放锁。
  • 但这种手动实现的自旋锁无法有效避免竞态条件,最终mails的结果会小于预期值。

内容的提问来源于stack exchange,提问作者Gopendra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 02:50:51