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
------解决方案--------------------
这是书上的一个例子,反映多线程操作共享变量时可能要线程竞争导致结果不对,因为在自增操作时,要经过三个步骤:
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; }
------解决方案--------------------