- 论坛徽章:
- 0
|
本帖最后由 iw1210 于 2013-04-17 16:03 编辑
int a; 一个线程写a,另一线程读a,如果不加锁,果然出现写了一半,读了一半的情况!
比如写线程里两条语句
a = 2;
a = 3;
在执行完 a = 2 还没执行 a = 3 完时,读线程去读a,读到的有可能就不是2!!!
例子:- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <assert.h>
- #define MAXVAL (~0)
- #define STARTVAL (MAXVAL-5)
- #define LOCK(mutex) //pthread_mutex_lock(&(mutex))
- #define UNLOCK(mutex) //pthread_mutex_unlock(&(mutex));
- pthread_mutex_t mtx;
- unsigned int a = STARTVAL;
- static void treadfun(void)
- {
- while(1)
- {
- LOCK(mtx);
- if(MAXVAL == a)
- a = STARTVAL;
- else
- a++;
- UNLOCK(mtx);
- }
- return;
- }
- int main()
- {
- int i;
- pthread_t tid[10];
- printf("MAXVAL = %u, STARTVAL = %u\n", MAXVAL, STARTVAL);
- pthread_mutex_init(&mtx, NULL);
- for(i=0; i<10; i++)
- {
- if(0 != pthread_create(&tid[i],NULL,(void *)treadfun,NULL))
- {
- fprintf(stderr,"Create thread error!\n");
- return -1;
- }
- }
- while(1)
- {
- printf("a = %u\n", a);
- LOCK(mtx);
- assert(STARTVAL <= a && a <= MAXVAL );
- UNLOCK(mtx);
- }
-
- pthread_mutex_destroy(&mtx);
- printf("test end.\n");
- return 0;
- }
复制代码 执行结果:
... ...
a = 4294967291
a = 4294967295
a = 4294967293
a = 4294967292
a = 4294967290
a = 4294967295
a = 4294967293
a = 4294967295
a = 4294967292
main: Assertion `((~0)-5) <= a && a <= (~0)' failed.
Aborted (core dumped)
|
|