1)、静态分配互斥量:
#include "stdio.h"
#include <stdlib.h>
#include <pthread.h>
#define N_CONSUMER 3 //消费者数量
#define N_PRODUCER 2 //生产者数量
#define C_SLEEP 1 //控制 consumer 消费的节奏
#define P_SLEEP 1 //控制 producer 生产的节奏
pthread_t ctid[N_CONSUMER];//消费者线程数组
pthread_t ptid[N_PRODUCER];//生产者线程数组
pthread_cond_t notFull,notEmpty;//定义条件变量,notFull缓冲区不满;notEmpty缓冲区不空
pthread_mutex_t buf = PTHREAD_MUTEX_INITIALIZER;//静态分配互斥量,用于锁住缓冲区
int begin = 0,end = 0, cnt = 0, max = 4;//从 begin 到 end(不含end) 代表产品,cnt 代表产品数量,max 代
表库房的容量,即最多生产多少产品
void * consumer(void * pidx)//consumer thread idx
{
printf("consumer thread id %d\n",*((int *)pidx));
while(1)
{
pthread_mutex_lock(&buf);
while(cnt == 0){//当缓冲区空时
pthread_cond_wait(¬Empty,&buf);//阻塞并等待不空的信号
}
printf("consume %d\n",begin);
begin = (begin+1)%max;
cnt--;
pthread_mutex_unlock(&buf);
sleep(C_SLEEP);
pthread_cond_signal(¬Full);
}
pthread_exit((void *)0);
}
void * producer(void * pidx)//producer thread idx
{
printf("producer thread id %d\n",*((int *)pidx));
while(1)
{
pthread_mutex_lock(&buf);
while(cnt == max){//当缓冲区满时
pthread_cond_wait(¬Full,&buf);
}
pthread_mutex_lock(&buf);
while(cnt == 0){//当缓冲区空时
pthread_cond_wait(¬Empty,&buf);//阻塞并等待不空的信号
}
printf("consume %d\n",begin);
begin = (begin+1)%max;
cnt--;
pthread_mutex_unlock(&buf);
sleep(C_SLEEP);
pthread_cond_signal(¬Full);
}
pthread_exit((void *)0);
}
void * producer(void * pidx)//producer thread idx
{
printf("producer thread id %d\n",*((int *)pidx));
while(1)
{
pthread_mutex_lock(&buf);
while(cnt == max){//当缓冲区满时
pthread_cond_wait(¬Full,&buf);
}
int main()
{
int i = 0;
for(i = 0; i < N_CONSUMER; i++)
{
int * j = (int *) malloc(sizeof(int));
*j = i;
if(pthread_create(&ctid[i],NULL,consumer,j) != 0)
{
perror("create consumer failed\n");
exit(1);
}
}
for(i = 0; i < N_PRODUCER; i++)
{
int * j = (int *) malloc(sizeof(int));
*j = i;
if(pthread_create(&ptid[i],NULL,producer,j) != 0)
{
perror("create producer failed\n");
exit(1);
}
}
while(1)
{
sleep(10);
}
return 0;
}2)、动态分配互斥量:
#include <stdlib.h>
#include <pthread.h>
struct foo {
int f_count;
pthread_mutex_t f_lock;
/* ... more stuff here ... */
};
struct foo * foo_alloc(void) /* allocate the object */
{
struct foo *fp;
if ((fp = malloc(sizeof(struct foo))) != NULL) {
fp->f_count = 1;
if (pthread_mutex_init(&fp->f_lock, NULL) != 0) {
free(fp);
return(NULL);
}
/* ... continue initialization ... */
}
return(fp);
}
void foo_hold(struct foo *fp) /* add a reference to the object */
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
void foo_rele(struct foo *fp) /* release a reference to the object */
{
pthread_mutex_lock(&fp->f_lock);
if (--fp->f_count == 0) { /* last reference */
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
本文探讨了静态与动态分配互斥量在多线程编程中的应用,通过消费者生产者模型展示了互斥量如何控制资源访问,确保线程安全。
1760

被折叠的 条评论
为什么被折叠?



