互斥量和死锁

    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都在等对方释放锁,于是就陷入死锁状态。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值