条件变量,信号量实现生产者消费者

本文探讨了C语言中条件变量和信号量两种并发控制机制的实现,通过实例展示了如何使用它们来管理生产者消费者问题。作者通过produser和consumer函数展示了条件变量的使用,而信号量则通过producer和consumer函数演示了资源同步。
摘要由CSDN通过智能技术生成

条件变量:

#include <stdio.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <assert.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/epoll.h>

struct msg{
	int num;
	struct msg *next;
};

struct msg *head;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t has_data = PTHREAD_COND_INITIALIZER;

void *produser(void *arg){
	while(1){
		struct msg *mp = malloc(sizeof(struct msg));
		mp->num = rand() % 1000 + 1;
		printf("---produce : %d\n", mp->num);
		pthread_mutex_lock(&mutex);
		mp->next = head;
		head = mp;
		pthread_mutex_unlock(&mutex);
		pthread_cond_signal(&has_data);
		sleep(rand() % 3);
	}
	return NULL;
}
void *consumer(void *arg){
	while(1){
		struct msg *mp;
		pthread_mutex_lock(&mutex);
		if(head == NULL) pthread_cond_wait(&has_data, &mutex);
		mp = head;
		head = mp->next;
		pthread_mutex_unlock(&mutex);
		printf("--------consumer : %d\n", mp->num);
		free(mp);
		sleep(rand() % 3);
	}
	return NULL;
}

int main(){

	srand(time(NULL));

	int ret;
	pthread_t pid, cid;
	ret = pthread_create(&pid, NULL, produser, NULL);
	ret = pthread_create(&cid, NULL, consumer, NULL);
	pthread_join(pid, NULL);
	pthread_join(cid, NULL);

	return 0;
}

信号量:

#include <stdio.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <assert.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/epoll.h>
#include <semaphore.h>

#define NUM 5

int queue[NUM];
sem_t blank_number, product_number;

void *producer(void *arg){
	int i = 0;
	while(1){
		sem_wait(&blank_number);
		queue[i] = rand() % 1000 + 1;
		printf("----Produce---%d\n", queue[i]);
		sem_post(&product_number);

		i = (i + 1) % NUM;
		sleep(0);
	}
}
void *consumer(void *arg){
	int i = 0;
	while(1){
		sem_wait(&product_number);
		printf("Consume---%d\n", queue[i]);
		queue[i] = 0;
		sem_post(&blank_number);
		i = (i + 1) % NUM;

		sleep(rand() % 3);
	}
}

int main(){

	pthread_t pid, cid;
	sem_init(&blank_number, 0, NUM);
	sem_init(&product_number, 0, 0);

	pthread_create(&pid, NULL, producer, NULL);
	pthread_create(&cid, NULL, consumer, NULL);

	pthread_join(pid, NULL);
	pthread_join(cid, NULL);

	sem_destroy(&blank_number);
	sem_destroy(&product_number);
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值