int a; 一个线程写a,另一线程读a,如果不加锁,果然出现写了一半,读了一半的情况!
比如写线程里两条语句
a = 2;a = 3;
在执行完 a = 2 还没执行 a = 3 完时,读线程去读a,读到的有可能就不是2!!!
直接上个例子(test.c):
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
#define MAXVAL (~0)
#define STARTVAL (MAXVAL-5)
#define NUMTHR 10
#define LOCK(mutex) //pthread_mutex_lock(&(mutex))
#define UNLOCK(mutex) //pthread_mutex_unlock(&(mutex));
pthread_mutex_t mtx;
int flag = 1;
unsigned int a = STARTVAL;
static void treadfun(void)
{
while(flag)
{
LOCK(mtx);
if(MAXVAL == a)
a = STARTVAL;
else
a++;
UNLOCK(mtx);
}
return;
}
int main()
{
int i;
unsigned int n;
pthread_t tid[NUMTHR];
printf("MAXVAL = %u, STARTVAL = %u\n", MAXVAL, STARTVAL);
pthread_mutex_init(&mtx, NULL);
for(i=0; i < NUMTHR; i++)
{
if(0 != pthread_create(&tid[i],NULL,(void *)treadfun,NULL))
{
fprintf(stderr,"Create thread error!\n");
return -1;
}
}
while(1)
{
LOCK(mtx);
//assert(STARTVAL <= a && a <= MAXVAL ); // 不加锁时,如果把这句打开,程序就会崩溃退出。
if(a < STARTVAL || a > MAXVAL)
{
printf("a = %u\n", a);
UNLOCK(mtx);
break;
}
UNLOCK(mtx);
}
flag = 0;
for(i=0; i < NUMTHR; i++)
pthread_join(tid[i],NULL);
pthread_mutex_destroy(&mtx);
printf("end.\n");
return 0;
}
执行结果:
MAXVAL = 4294967295, STARTVAL = 4294967290
a = 856431
end.
注意:a的值距离 MAXVAL 和 STARTVAL 甚远。
如果把两个锁定义打开(下面),程序就不会退出终止。
#define LOCK(mutex) pthread_mutex_lock(&(mutex))
#define UNLOCK(mutex) pthread_mutex_unlock(&(mutex));