【发布时间】:2017-03-15 23:56:05
【问题描述】:
我创建了如下的生产者/消费者代码
class CTest{
public:
void producer( int i ){
unique_lock<mutex> l(m);
q.push(i);
if( q.size() )
cnd.notify_all();
}
void consumer(int i ){
unique_lock<mutex> l(m);
while( q.empty() ){
cnd.wait(l );
}
if( q.empty())
return;
cout << "IM AWAKE :" << i << endl;
int tmp = q.front();
q.pop();
l.unlock();
cout << "Producer got " << tmp << endl;
}
void ConsumerInit( int threads ){
for( int i = 0; i < threads; i++ ){
thrs.push_back(thread(&CTest::consumer, this ,i));
}
}
void waitForTHreads(){
for( auto &a : thrs )
a.join();
}
void printQueue(){
while( ! q.empty()){
int tmp = q.front();
q.pop();
cout << "Queue got " << tmp << endl;
}
}
private:
queue<int> q;
vector<thread> thrs;
mutex m;
condition_variable cnd;
};
和主要的
int main(){
int x;
CTest t;
int counter = 0;
while( cin >> x ){
if( x == 0 ){
cout << "yay" << endl;;
break;
}
if( x == 1)
t.producer(counter++);
if( x == 2 )
t.ConsumerInit(5);
}
t.waitForTHreads();
t.printQueue();
return 0;
}
这段代码是做什么的,当用户输入“1”时,它将向队列添加数字,当用户输入“2”时,会产生5个线程来从队列中检索数据并打印它。但是,当我输入时,我的问题如下 6个数字,由于只产生了5个线程,因此只打印了其中的5个,我想做的是线程从队列中检索数据,打印int,然后再次等待它是否可以打印另一个数据。这样一来,所有 N > 5 个数字都将仅用 5 个线程打印。
我的问题是,如何实现这一目标的标准方法是什么?我读了一些文档,但没有找到/想不出好的解决方案。这样的问题是如何解决的?
当我尝试创建简单的线程池时:
void consumer(int i ){
while(true){
{
unique_lock<mutex> l(m);
while( q.empty() ){
cnd.wait(l );
}
if( q.empty())
return;
cout << "IM AWAKE :" << i << endl;
int tmp = q.front();
q.pop();
cout << "Producer " << i << " got " << tmp << endl;
} //consumer(i);
}
}
并输入N个数字,所有数字都由一个线程处理。 感谢您的帮助!
【问题讨论】:
-
可能你所有的项目都被一个线程消耗掉了,因为该线程在下一个线程有机会醒来之前就完成了所有处理。
标签: c++ multithreading mutex