linux——与互斥锁相关api

        互斥量(mutex)从本质上来说是一把锁。在访问共享资源前对互斥量进行加锁,在访问完成后释放互斥量。

        对互斥量进行枷锁后,任何其他试图再次对互斥量加锁的线程将会被阻塞直到当前线程释放该互斥锁。如果释放互斥锁时有多个线程阻塞,所有在该互斥锁上的阻塞线程都会变成可运行状态,第一个变成可运行状态的线程可以对互斥量加锁,其他线程将会看到互斥锁依然被锁住,只能回去等待它重新变为可用。在这种方式下,每次只有一个线程可以向前运行。

创建锁及销毁互斥锁

#include <pthread.h>

int pthread_mutex_init(pthread_mutex_t * restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t mutex);
//返回:若成功返回0,否则返回错误编号

        互斥量用pthread_mutex_t数据类型表示。在使用互斥量前必须对它进行初始化,可以通过调用pthread_mutex_init函数进行初始化。如果动态地分配互斥量(例如通过调用malloc函数),那么在释放内存前需要调用 pthread_mutex_destroy.

        要用默认的属性初始化互斥量,只需要把attr设置为NULL。

加锁及解锁:

#include <pthread.h>

int pthread_mutex_lock(pthread_mutex_t mutex);
int pthread_mutex_trylock(pthread_mutex_t mutex);
int pthread_mutex_unlock(pthread_mutex_t mutex);

        如果线程不希望被阻塞,它可以使用pthread_mutex_trylock尝试对互斥量进行加锁。如果调用pthread_mutex_trylock时互斥量处于未锁住状态,那么pthread_mutex_trylock将锁住互斥量,不会出现阻塞并返回0,否则pthread_mutex_trylock就会失败,不能锁住互斥量,而返回EBUSY。

代码演示:

#include <stdio.h>
#include <pthread.h>

//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
pthread_mutex_t mutex;

int g_data=0;

void *func1(void *arg)
{
	int i;
	pthread_mutex_lock(&mutex);

	for(i=0;i<5;i++){
	printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
	printf("t1:param is %d\n",*((int*)arg));
	sleep(1);
	}

	pthread_mutex_unlock(&mutex);
}
void *func2(void *arg)
{
        pthread_mutex_lock(&mutex);

        printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
        printf("t2:param is %d\n",*((int*)arg));

        pthread_mutex_unlock(&mutex);

}


int main()
{
	int ret;
	int param=100;
	pthread_t t1;
	pthread_t t2;
	
	pthread_mutex_init(&mutex,NULL);

	ret=pthread_create(&t1,NULL,func1,(void*)&param);	
	if(ret==0){
		printf("main:create t1 success\n");
	}
        ret=pthread_create(&t2,NULL,func2,(void*)&param);
        if(ret==0){
                printf("main:create t2 success\n");
        }

	
	printf("main %ld \n",(unsigned long)pthread_self());

	pthread_join(t1,NULL);
	pthread_join(t2,NULL);

	pthread_mutex_destroy(&mutex);

	return 0;
}

运行结果:

main:create t1 success
main:create t2 success
main 140665699079936 
t1:140665690793728 thread is create
t1:param is 100
t1:140665690793728 thread is create
t1:param is 100
t1:140665690793728 thread is create
t1:param is 100
t1:140665690793728 thread is create
t1:param is 100
t1:140665690793728 thread is create
t1:param is 100
t2:140665682401024 thread is create
t2:param is 100

当t1进行上锁后,t2一直处于阻塞状态,t1解锁后,t2运行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值