线程的互斥

线程的互斥:使用线程互斥锁

初始化锁
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
功能: 初始化互斥锁
参数:
mutex : 锁
attr : NULL 默认为互斥
返回值: 成功返回0
失败返回 error number 设置error

  • *》使用锁

  • #include <pthread.h>

  • int pthread_mutex_lock(pthread_mutex_t *mutex);

  • 功能: 使用锁

  • 参数:

  • mutex : 锁

  • 返回值: 成功返回0

  • 失败返回 error number 设置error

  • 》解开锁

  • #include <pthread.h> int pthread_mutex_unlock(pthread_mutex_t
    *mutex);
    功能: 解开锁
    参数: mutex : 锁
    返回值: 成功返回0
    失败返回 error number 设置error

  • *》销毁锁

  • #include <pthread.h> int pthread_mutex_destroy(pthread_mutex_t *mutex);

  • 功能: 销毁锁

  • 参数:

  • mutex: 锁
    返回值: 成功返回0
    失败返回 error number 设置error

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>

int a;
int b;
pthread_mutex_t pmt;
void *show1(void *arg)
{
	while(1){
		printf("1\n");
		pthread_mutex_lock(&pmt);   //使用锁
		a++,b++;
		pthread_mutex_unlock(&pmt);   //释放锁
	}
	pthread_exit(NULL);
	return NULL;
}

void *show2(void *arg)
{
	while(1){
		printf("2\n");
		pthread_mutex_lock(&pmt);   //使用锁
		if(a==b)
			printf("a==b\n");
		else
			printf("a!=b\n");
		pthread_mutex_unlock(&pmt);   //释放锁
	}
	pthread_exit(NULL);
	
	return NULL;
}

int main()
{
	if(pthread_mutex_init(&pmt,NULL)){
		perror("pthread_mutex_init error");
		exit(-1);
	}
    ///创建线程1
	pthread_t thread1;
	if(pthread_create(&thread1,NULL,show1,NULL)){
		perror("pthread_create error");
		exit(-1);		
	}
	设置分离属性
	if(pthread_detach(thread1)){
		perror("pthread_detach error");
		exit(-1);
	}
	    ///创建线程2
	pthread_t thread2;
	if(pthread_create(&thread2,NULL,show2,NULL)){
		perror("pthread_create error");
		exit(-1);		
	}
	设置分离属性
	if(pthread_detach(thread2)){
		perror("pthread_detach error");
		exit(-1);
	}
	while(1);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值