示例
创建两个线程,分别对全局变量进行 +1 操作,分别对比使用互斥锁和没有使用互斥锁
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
static int global = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *do_thread(void *arg)
{
int loops = *(int *)arg;
int i,tmp = 0;
for (i = 0;i < loops;i++){
pthread_mutex_lock(&mutex);
tmp = global;
tmp++;
global = tmp;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc,char *argv[])
{
int err,i = 0;
pthread_t tid[2] = {0};
int loops = 0;
if (argc != 2){
fprintf(stderr,"Usage : < %s > < count loops>\n",argv[0]);
exit(EXIT_FAILURE);
}
loops = atoi(argv[1]);
for (i = 0;i < 2;i++){
err = pthread_create(&tid[i],NULL,do_thread,&loops);
if (err != 0){
fprintf(stderr,"[ERROR] pthread_create(): < %s > \n",strerror(err));
exit(EXIT_FAILURE);
}
}
pthread_join(tid[0],NULL);
pthread_join(tid[1],NULL);
printf("global = %d\n",global);
return 0;
}
- 没有使用互斥锁时,输出结果如下:
./a.out 1000000
global = 1321859
- 使用互斥锁后,输出结果如下:
global = 2000000
练习
使用互斥锁验证上述示例