#include <iostream>
#include <condition_variable>
#include <pthread.h>
#include <thread>
#include <unistd.h>
#include <mutex>
using namespace std;
template <typename T>
class CircleQueue {
public:
CircleQueue(int sz) : m_head(0), m_tail(0), m_max_sz(sz+1), m_cur_sz(0) {
m_array = new T[m_max_sz];
pthread_cond_init(&m_cv, NULL);
pthread_mutex_init(&m_mtx, NULL);
}
~CircleQueue() {
if(m_array) {
delete[] m_array;
}
pthread_mutex_destroy(&m_mtx);
pthread_cond_destroy(&m_cv);
}
bool isFull() {
pthread_mutex_lock(&m_mtx);
if(m_cur_sz >= m_max_sz) {
pthread_mutex_unlock(&m_mtx);
return true;
}
pthread_mutex_unlock(&m_mtx);
return false;
}
bool isEmpty() {
pthread_mutex_lock(&m_mtx);
if(m_cur_sz == 0) {
pthread_mutex_unlock(&m_mtx);
return true;
}
pthread_mutex_unlock(&m_mtx);
return false;
}
bool push(T val) {
pthread_mutex_lock(&m_mtx);
if(m_cur_sz >= m_max_sz) {
pthread_cond_broadcast(&m_cv);
pthread_mutex_unlock(&m_mtx);
return false;
}
m_array[m_tail] = val;
m_tail = (m_tail + 1) % m_max_sz;
++m_cur_sz;
pthread_cond_broadcast(&m_cv);
pthread_mutex_unlock(&m_mtx);
return true;
}
bool pop(T& val) {
pthread_mutex_lock(&m_mtx);
while(m_cur_sz <= 0) {
if(!pthread_cond_wait(&m_cv, &m_mtx)) {
pthread_mutex_unlock(&m_mtx);
return false;
}
}
val = m_array[m_head];
m_head = (m_head + 1) % m_max_sz;
--m_cur_sz;
pthread_mutex_unlock(&m_mtx);
return true;
}
private:
pthread_cond_t m_cv;
pthread_mutex_t m_mtx;
T* m_array;
int m_cur_sz;
int m_head, m_tail, m_max_sz;
};
CircleQueue<int> cq(5);
void produce() {
int num = 0;
while(1) {
auto ret = cq.push(num);
if(ret) {
cout << std::this_thread::get_id() << " : " << num << " - " << "push successfully" << endl;
++num;
}
}
}
void cosumer() {
while(1) {
int num = 0;
auto ret = cq.pop(num);
if(ret)
cout << std::this_thread::get_id() << " : " << num << " - pop successfully" << endl;
else
cout << "Empty" << endl;
}
}
int main() {
thread t1(produce);
thread t3(cosumer);
t1.join();
t3.join();
return 0;
}
生产者消费者模型c++
最新推荐文章于 2025-04-09 19:42:28 发布