#include <iostream>
#include <pthread.h>
#include <mutex>
#include <queue>
#include <unistd.h>
#define CAPACITY 10
#define THREADCOUNT 2
// 生产者和消费者模型
class BlockQueue
{
public:
BlockQueue()
{
capacity_ = CAPACITY;
pthread_mutex_init(&lock_, NULL);
pthread_cond_init(&cons, NULL);
pthread_cond_init(&prod, NULL);
}
// 队列入元素
void Push(int data)
{
pthread_mutex_lock(&lock_);
while(que_.size() >= capacity_)
{
pthread_cond_wait(&prod, &lock_);
}
que_.push(data);
pthread_mutex_unlock(&lock_);
pthread_cond_signal(&cons);
}
void Pop(int* data)
{
pthread_mutex_lock(&lock_);
while(que_.empty())
{
pthread_cond_wait(&cons, &lock_);
}
*data = que_.front();
que_.pop();
pthread_mutex_unlock(&lock_);
pthread_cond_signal(&prod);
}
~BlockQueue()
{
pthread_mutex_destroy(&lock_);
pthread_cond_destroy(&cons);
pthread_cond_destroy(&prod);
}
private:
std::queue<int> que_;
size_t capacity_;
pthread_mutex_t lock_;
pthread_cond_t cons;
pthread_cond_t prod;
};
void* ConsStart(void* arg)
{
BlockQueue* bq = (BlockQueue*)arg;
while(1)
{
int data;
bq->Pop(&data);
printf("i am thread %p, i consume %d\n", pthread_self(), data);
}
return NULL;
}
void* ProdStart(void* arg)
{
BlockQueue* bq = (BlockQueue*)arg;
int data = 0;
while(1)
{
bq->Push(data);
data++;
printf("i am thread %p, i product %d\n", pthread_self(), data);
}
return NULL;
}
int main()
{
pthread_t cons[THREADCOUNT], prod[THREADCOUNT];
BlockQueue* bq = new BlockQueue();
for(int i = 0; i < THREADCOUNT; ++i)
{
int ret = pthread_create(&prod[i], NULL, ConsStart, (void*)bq);
if(ret < 0)
{
perror("pthread create !!!");
return -1;
}
ret = pthread_create(&cons[i], NULL, ProdStart, (void*)bq);
if(ret < 0)
{
perror("pthread create !!!");
return -1;
}
}
for(int i = 0; i < THREADCOUNT; ++i)
{
pthread_join(prod[i], NULL);
pthread_join(prod[i], NULL);
}
return 0;
}
【linux】生产者与消费者模型实现代码
最新推荐文章于 2024-04-15 18:29:55 发布