我目前正在研究一个模拟扩展 Producer-Worker 模型的问题。在这个问题中,有 3 名工人和 3 种工具可用,而工人要工作,他们需要 2 种工具(和材料,但这些无关紧要)。如果保险库中有 >=2 个工具,工人将拿 2 个。否则,他们将等待一个条件变量,当有 >=2 时将发出信号。
这对 2 名工人来说很好:一名将工作然后将工具归还到保险库,另一名等待的工人将被唤醒并拿走 2 件工具。问题是,有 3 名工人,总会有一个人饿着要得到工具。
经过一些测试,我注意到等待条件变量的线程是以堆栈形式构造的。有没有可能让它排队?(1等,2等,3等。1醒了要再造,要在2和3后面等。)
这是一个示例输出。代码太长了,如果真的需要,我会发布它。有 3 个工作线程和 1 个工具互斥锁。挨饿的人每跑一次都不一样。
1 Tools taken. Remaining: 1
2 Waiting on tools...
3 Waiting on tools...
1 Operator Product made. Tools returned. Tools now:3
3 Tools taken. Remaining: 1
1 Waiting on tools...
3 Materials returned for switch.
3 Operator Product made. Tools returned. Tools now:3
1 Tools taken. Remaining: 1
3 Waiting on tools...
1 Materials returned for switch.
1 Operator Product made. Tools returned. Tools now:3
3 Tools taken. Remaining: 1
1 Waiting on tools...
3 Materials returned for switch.
3 Operator Product made. Tools returned. Tools now:3
1 Tools taken. Remaining: 1
3 Waiting on tools...
1 Materials returned for switch.
1 Operator Product made. Tools returned. Tools now:3
3 Tools taken. Remaining: 1
1 Waiting on tools...
3 Materials returned for switch.
3 Operator Product made. Tools returned. Tools now:3
1 Tools taken. Remaining: 1
3 Waiting on tools...
1 Materials returned for switch.
...
(如您所见,2 从未获得工具...)
更新:2013/07/05 我添加了一些代码。
int tools = 3; //global
string last; //current last product on output buffer
mutex toolsMutex;
mutex matSearchMutex;
int main(){
//Initializing Producers
Producer prod1(1);
Producer prod2(2);
Producer prod3(3);
thread p1(processor,1);
thread p2(processor,2);
thread p3(processor,3);
p1.detach();
p2.detach();
p3.detach();
while(true){//forever running
}
return 0;
}
处理器:
//Processor method
void processor(int i){
srand(time(NULL));
while (true){ //forever running
bool hasTools = false;
bool productMade = false;
while (productMade == false){ //while product has yet to be made.
//choose what to make...
if (hasTools == false){
thread matT(getMaterials,whatToMake);
thread toolT(getTools,i);
toolT.join();
matT.join();
hasTools = true;
}
else{ //tools acquired but no materials
thread matT(getMaterials,whatToMake);
matT.join();
}
if (recordedLast.compare(last) != 0){
//return materials and acquire new ones the next run
continue;
}
else {
makeProduct(whatToMake);
unique_lock<mutex> locker(toolMutex);
tools = tools + 2;
cout << i << " Operator Product made. Tools returned. Tools now:" << tools << endl;
productMade = true;
if (tools >=2) toolsCV.notify_one();
}
//done processing
}
}
}
制作产品:
void makeProduct(int i){
unique_lock<mutex> mainMatLock(matSearchMutex);
// make product according to i
this_thread::sleep_for(chrono::milliseconds(rand() % 1000 + 10));
}
获取工具:
void getTools(int i){
unique_lock<mutex> locker(toolMutex);
if (tools <2){
cout << i << " Waiting on tools..." << endl;
toolsCV.wait(locker);}
tools = tools - 2;//tools acquired
cout << i <<" Tools taken. Remaining: " << tools << endl;
}
感谢那些已经回复的人。今晚我将尝试使用多个条件变量来实现等待队列。
(PS 有没有更好的方法在 Stack Overflow 上进行代码格式化?除了四个空格...