1、互斥量可以理解为一把锁,在访问共享资源的时候,通过加锁,来确保在同一时间只有一个线程可以访问该共享资源。这里主要总结一下Linux下锁的使用,并通过锁的使用来进一步加深对互斥量的理解。
2、通过具体实例来说明用法:
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
pthread_mutex_t testlock;
pthread_t test_thread;
void *test(void*)
{
pthread_mutex_lock(&testlock);
printf("thread Test\n");
pthread_mutex_unlock(&testlock);
}
int main()
{
pthread_mutex_init(&testlock, NULL);
pthread_mutex_lock(&testlock);
printf("main proc..\n");
int ret = pthread_create(&test_thread, NULL, test, NULL);
if(ret == -1) printf("createthread error!");
sleep(2);
pthread_mutex_unlock(&testlock);
sleep(2);
return 0;
}
从这段代码可以看到,test线程必须等到主进程释放锁之后才能向下执行。
3、死锁
如果对一个互斥量加锁两次,就会出现死锁,在上面的代码中重复一句加锁操作:
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
pthread_mutex_t testlock;
pthread_t test_thread;
void *test(void*)
{
pthread_mutex_lock(&testlock);
printf("thread Test\n");
pthread_mutex_unlock(&testlock);
}
int main()
{
pthread_mutex_init(&testlock, NULL);
pthread_mutex_lock(&testlock);
pthread_mutex_lock(&testlock);
printf("main proc..\n");
int ret = pthread_create(&test_thread, NULL, test, NULL);
if(ret == -1) printf("createthread error!");
sleep(2);
pthread_mutex_unlock(&testlock);
sleep(2);
return 0;
}
运行后就会发现死锁。接着考虑两个线程之间的死锁:
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
pthread_mutex_t testlock1,testlock2;
pthread_t test_thread1,test_thread2;
void *test1(void*)
{
pthread_mutex_lock(&testlock1);
printf("thread Test1..\n");
sleep(1);
pthread_mutex_lock(&testlock2);
printf("get Testlock2\n");
pthread_mutex_unlock(&testlock2);
pthread_mutex_unlock(&testlock1);
}
void *test2(void*)
{
pthread_mutex_lock(&testlock2);
printf("thread Test2..\n");
sleep(1);
pthread_mutex_lock(&testlock1);
printf("get testlock1\n");
pthread_mutex_unlock(&testlock1);
pthread_mutex_unlock(&testlock2);
}
int main()
{
pthread_mutex_init(&testlock1, NULL);
pthread_mutex_init(&testlock2, NULL);
printf("main proc..\n");
int ret1 = pthread_create(&test_thread1, NULL, test1, NULL);
int ret2 = pthread_create(&test_thread2, NULL, test2, NULL);
if(ret1==-1 || ret2==-1) printf("createthread error!");
sleep(5);
return 0;
}
这里,线程test1和线程test2都在等对方释放锁,于是就陷入死锁状态。