互斥锁
类型
pthread_mutex_t
互斥锁基本操作
函数 | 描述 | |
---|---|---|
[[pthread_mutex_init | pthread_mutex_init]] | 初始化互斥锁 |
[[pthread_mutex_lock | pthread_mutex_lock]] | 阻塞申请互斥锁 |
[[pthread_mutex_unlock | pthread_mutex_unlock]] | 释放互斥锁 |
[[pthread_mutex_trylock | pthread_mutex_trylock]] | 非阻塞申请互斥锁 |
[[pthread_mutex_destroy | pthread_mutex_destroy]] | 销毁互斥锁 |
互斥锁属性的基本操作
函数 | 描述 | |
---|---|---|
[[pthread_mutexattr_init | pthread_mutexattr_init]] | 初始化属性对象 |
[[pthread_mutexattr_destroy | pthread_mutexattr_destroy]] | 销毁属性对象 |
[[pthread_mutexattr_settype | pthread_mutexattr_settype]] | 设置属性对象的属性 |
[[pthread_mutexattr_gettype | pthread_mutexattr_gettype]] | 获得属性对象的属性 |
示例:基于互斥锁实现生产者与消费者模型
要求:1、主线程作为消费者线程 2、n个子线程作为生产者线程
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
static pthread_mutex_t mutex;
static int product_number=0;
void * thread_handle(void *arg){
int loopCount=atoi((char*)arg);
for(int i=0;i<loopCount;i++){
pthread_mutex_lock(&mutex);
printf("生产者: product_number=%d\n",++product_number);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc,char* argv[]){
if(argc<2){
return 1;
}
pthread_t thread[argc-1];
int ret=0;
int production_number=0;
int consumption_number=0;
for(int i=0;i<argc-1;i++){
production_number+=atoi(argv[i+1]);
ret=pthread_create(thread+i,NULL,thread_handle,(void *)argv[i+1]);
if(ret!=0){
exit(EXIT_FAILURE);
}
}
while(1){
pthread_mutex_lock(&mutex);
while(product_number>0){
printf("消费者:product_number=%d consumption_number=%d\n",--pro duct_number,++consumption_number);
}
pthread_mutex_unlock(&mutex);
if(production_number==consumption_number){
break;
}
}
for(int i=0;i<argc-1;i++){
pthread_join(thread[i],NULL);
}
pthread_mutex_destroy(&mutex);
return 0;
}