以下代码未经编译调试,可能编译不过。只是大概写了下实现。
#include <iostream>
#include <queue>
using namespace std;
class CBuffer
{
private:
mutex m_mutex;
condition_variable_any cond_put;
condition_variable_any cond_get;
queue<int> q_que;
int n_wait_read;
int n_capacity;
bool IsFull()
{
return (n_wait_read == n_capacity);
}
bool IsEmpty()
{
return (n_wait_read == 0);
}
public:
CBuffer(int n_size)
: n_wait_read(0)
: n_capacity(n_size)
{
}
void put(int x)
{
{
auto lck = make_unique_lock(m_mutex);
cond_put.wait(lck, [&]()->bool{ return !IsFull(); });
q_que.push(x);
n_wait_read++;
}
cond_get.notify_one();
}
void get(int *x)
{
{
auto lck = make_unique_lock(m_mutex);
cond_get.wait(lck, [&]()->bool{ return !IsEmpty(); });
n_wait_read--;
*x = q_que.front();
q_que.pop();
}
cond_put.notify_one();
}
}
CBuffer buf(5);
void Producer(int n)
{
for (int i = 0; i < n; i++)
{
cout << "put" << i << endl;
buf.put(i);
}
}
void Consumer(int n)
{
int x;
for( int i = 0; i < n; i++)
{
buf.get(&x);
cout << "get" << x << endl;
}
}
int main()
{
thread_group tg;
tg.create_thread(bind(Producer, 20));
tg.create_thread(bind(Consumer, 10));
tg.create_thread(bind(Consumer, 10));
tg.join_all();
return 0;
}