顾名思义,在多线程下,用来锁定资源使用权限。
我们先看一段代码:
#include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<unistd.h>
int count =0;
void *func(void* argc)
{
for(int i=0; i<3; i++)
{
printf("[before] tid:%d count:%d\n", pthread_self(), count);
count++; printf("[after] tid:%d count:%d\n", pthread_self(), count); }
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1, NULL, func, NULL);
pthread_create(&t2, NULL, func, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
t1 t2两个线程可以同时修改count,所以很难得到我们希望的结果。
[before] tid:1845761792 count:0
[after] tid:1845761792 count:1
[before] tid:1845761792 count:1
[after] tid:1845761792 count:2
[before] tid:1845761792 count:2
[before] tid:1837369088 count:0
[after] tid:1837369088 count:4
[before] tid:1837369088 count:4
[after] tid:1837369088 count:5
[before] tid:1837369088 count:5
[after] tid:1837369088 count:6
[after] tid:1845761792 count:3
如果希望一个线程在修改资源时,其他线程无法获取资源的修改权时,可以使用互斥锁来实现。
修改一下代码:
#include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<unistd.h>
int count =0;
pthread_mutex_t mutex;
void *func(void* argc)
{
for(int i=0; i<3; i++)
{
pthread_mutex_lock(&mutex);
printf("[before] tid:%d count:%d\n", pthread_self(), count);
count++;
printf("[after] tid:%d count:%d\n", pthread_self(), count);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_mutex_init(&mutex, NULL); // 初始化互斥锁
pthread_t t1,t2;
pthread_create(&t1, NULL, func, NULL);
pthread_create(&t2, NULL, func, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
结果:
[before] tid:806139648 count:0
[after] tid:806139648 count:1
[before] tid:806139648 count:1
[after] tid:806139648 count:2
[before] tid:806139648 count:2
[after] tid:806139648 count:3
[before] tid:797746944 count:3
[after] tid:797746944 count:4
[before] tid:797746944 count:4
[after] tid:797746944 count:5
[before] tid:797746944 count:5
[after] tid:797746944 count:6