1.知识点
pthread_mutex_t mutex //创建互斥区
pthread_mutex_init(); //初始化互斥区
pthread_mutex_lock(&mutex) //互斥区上锁
pthread_mutex_unlock(&mutex) //互斥区解锁
ps:当一个线程执行了pthread_mutex_lock(),但是未执行unlock,另一个线程执行到pthread_mutex_lock()会被阻塞
pthread_join(consumer,NULL); //在main函数中调用这句话后主线程变成阻塞状态,直到consumer线程结束返回。
pthread_mutex_trylock()的使用:这个函数是非阻塞调用模式, 也就是说, 如果互斥量没被锁住, trylock函数将把互斥量加锁, 并获得对共享资源的访问权限; 如果互斥量被锁住了, trylock函数将不会阻塞等待而直接返回EBUSY, 表示共享资源处于忙状态。
2.实例代码
#include<pthread.h>
#include<sched.h>
#include<stdio.h>
#include<unistd.h>
void * producter_f (void *arg); //生产者
void * consumer_f1(void *arg); //1消费者
int buffercount=10; //缓冲区计数
pthread_mutex_t mutex; //创建互斥区
int running=1;
int main(void)
{
pthread_t consumer_t1; //消费者运行参数
pthread_t producter_t; //生成者进程
pthread_mutex_init(&mutex,NULL); //初始化互斥区
pthread_create(&producter_t,NULL,(void*)producter_f,NULL);//创建生产者进程
pthread_create(&consumer_t1,NULL,(void*)consumer_f1,NULL);//1创建消费者进程
usleep(1); //等待线程创建
running=0;
pthread_join(consumer_t1,NULL); //等待消费者进程结束
pthread_join(producter_t,NULL); //等待生产者进程结束
pthread_mutex_destroy(&mutex); //释放临界区资源
return 0;
}
void* producter_f(void *arg)
{
while(running) //生产者写入上锁
{
pthread_mutex_lock(&mutex); //对缓冲区上锁
buffercount++;
printf("当前缓存为:%d\n",buffercount);
pthread_mutex_unlock(&mutex); //解锁
}
}
void* consumer_f1(void * arg)
{
while(running)
{
pthread_mutex_lock(&mutex); //保护数据一次只有一个线程操作
buffercount--;
printf("当前缓存为:%d\n",buffercount);
pthread_mutex_unlock(&mutex); //解锁
}
}
3.测试结果
这里明显消费者进程抢夺能力强