linux c-multi-threaded producer and consumer model

linux c-multi-threaded producer and consumer model

Schematic diagram

Insert picture description here
In fact, this model is to notify one receiving and one sending, the lock is to solve internal contradictions, and the semaphore solves external contradictions.

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/select.h>
#include <vector>
#include <semaphore.h>
#include <iostream>
using namespace std;

#define pthread_sum 10
int gs;
sem_t gsem_produce;
sem_t gsem_custom;
pthread_mutex_t pro_mutex;//生产者互斥量
pthread_mutex_t cus_mutex;//消费者互斥量
//生产者
void* add (void* num) 
{
	//生产蛋糕
	cout << "make cake  id:" << pthread_self() << endl;
	sem_wait(&gsem_produce);
	pthread_mutex_lock(&pro_mutex);
	gs++;
	cout << "make cake...:" <<gs<<":"<< pthread_self() << endl;
	sleep(2);
	pthread_mutex_unlock(&pro_mutex);
	sem_post(&gsem_custom);//数量加一
	return NULL;

}
//消费者
void* sub(void* num)
{
	//等蛋糕的
	cout << "wait cake >>>id:" << pthread_self() << endl;
	sem_wait(&gsem_custom);
	pthread_mutex_lock(&cus_mutex);
	gs--;
	cout << "eat cake..." <<gs<<"nun:"<<pthread_self()<< endl;
	pthread_mutex_unlock(&cus_mutex);
	sem_post(&gsem_produce);//数量加一
	return NULL;

}
int main() 
{
	
	pthread_mutex_init(&pro_mutex,NULL);
	pthread_mutex_init(&cus_mutex, NULL);
	pthread_t pd[pthread_sum];
	sem_init(&gsem_produce,0,5);//第三个参数 为0就走不了  sempost只能为正的  一般设为1 第二个参数是初始值是多少 盘子
	sem_init(&gsem_custom, 0, 0);//消费者 初始化为0 蛋糕
	int i;
	int ret;
	for (i=0;i<5;i++) 
	{
	
		ret=pthread_create(&pd[i], NULL,add, NULL);
		if (ret!=0) 
		{
			cout << strerror(ret) << endl;
			return 0;
		
		}
	
	}
	for (i = 5; i < 10; i++)
	{

		ret = pthread_create(&pd[i], NULL, sub, NULL);
		if (ret != 0)
		{
			cout << strerror(ret) << endl;
			return 0;

		}

	}
	for (i = 0; i < 5; i++)
	{
	
		pthread_join(pd[i], NULL);
	
	}
	sleep(2);
	cout << "thread end" << endl;
	return 0;


}

Guess you like

Origin blog.csdn.net/z15005953031/article/details/113979370