linux多线程共享变量没出现预期的竞争

linux多线程共享变量没有出现预期的竞争
这是书上的一个例子,反映多线程操作共享变量时可能要线程竞争导致结果不对,因为在自增操作时,要经过三个步骤:
1.本地栈读到寄存器
2.寄存器运算
3.将寄存器去处结果存回本地栈
若线程1的第三步还没完成时,线程2就执行了第1步,读到了“脏”数据,程序执行结果应该不为20000000
可是此程序执行结果总为20000000 能不能解释为什么会这样,谢啦!

#include <stdio.h>
#include <stdlib.h> // for exit
#include <pthread.h> //for pthread_create

#include <semaphore.h>

#define NITERS 10000000
void *count (void *arg);
unsigned int cnt = 0;

int main ()
{
pthread_t tid1, tid2;

pthread_create (&tid1, NULL, count, NULL);
pthread_create (&tid2, NULL, count, NULL);
 
pthread_join (tid1, NULL);
pthread_join (tid2, NULL);
 
printf ("cnt:%d\n", cnt);
exit (0);
}

void *count (void *arg)
{
int i = 0;
for (; i < NITERS; i++)

cnt++;
}
return NULL;
}

Makefile执行的结果是:
gcc -c example.c -o example.o 
example.c:34:1: warning: no newline at end of file
gcc -o tt example.o -lpthread



------解决方案--------------------
C/C++ code
改成这样, 效果很明显:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define NITERS 10000000
void *count (void *arg);
volatile unsigned int cnt = 0;

int main ()
{
pthread_t tid1, tid2;

pthread_create (&tid1, NULL, count, NULL);
pthread_create (&tid2, NULL, count, NULL);
 
pthread_join (tid1, NULL);
pthread_join (tid2, NULL);
 
printf ("cnt:%d\n", cnt);
exit (0);
}

void *count (void *arg)
{
volatile int i = 0;
for (; i < NITERS; i++)
{ 
cnt++;
}
return NULL;
}

------解决方案--------------------
探讨

1楼和四楼,可能是我没说明清楚意思:问题的竞争在于两个线程可能同时执行cnt++,而这个操作不是原子操作,线程1将cnt读到寄存器后还没处理完时休眠了,线程2又去执行cnt++,这时cnt的结果就会不正确了。

二楼:你的解释很有道理,能告诉我你是怎么看到汇编代码了的吗,我是小菜鸟一个,嘿嘿~

三楼:我用你的代码执行后,大部分时候结果还是为20000000,但是也有部分时候不为20000……