全局变量未更新pthread

时间:2016-03-28 15:52:32

标签: c pthreads

我写了这个c程序:

int counter = 0;

void* increment()
{
  int maxI = 10000;
  int i;
  for (i = 0; i < maxI; ++i) { counter++; }
}

int main()
{
  pthread_t thread1_id;
  pthread_t thread2_id;
  pthread_create (&thread1_id,NULL,&increment,NULL);
  pthread_create (&thread2_id,NULL,&increment,NULL);
  pthread_join (thread1_id,NULL);
  pthread_join (thread2_id,NULL);
  printf("counter = %d\n",counter);
  return 0;
}

结果我得到:counter = 10000

为什么?我会期待更大的东西而不是因为我使用两个线程,我怎么能纠正它

PS:我知道会有竞争条件!

编辑:volatile int counter似乎解决了问题:)

1 个答案:

答案 0 :(得分:0)

预测带有错误的代码将会非常困难。最有可能的是,编译器正在优化您的increment函数以将counter保留在寄存器中。但是你必须查看生成的汇编代码才能确定。

相关问题