我想提出一些解决这一僵局的建议:
3 operators, each is given 2 of 3 different materials at random: 1, 2, 3
3 tools, each material needs a different tool to process by an operator.
material 1 needs tool 1
material 2 needs tool 2
material 3 needs tool 3
Each operator needs to wait for the proper tools to process the materials.
i.e. If an operator has taken material 1,2, he needs tool 1,2可能会出现僵局:
operator 1 has taken material 1,2, waiting for tool 1,2
operator 2 has taken material 2,3, waiting for tool 2,3
operator 3 has taken material 3,1, waiting for tool 3,1没有一个操作人员可以同时获得这两种工具,操作人员应该做什么?
提案
创建一个全局变量来记录操作人员最近采取的6种材料。如果每个材料出现两次(例如1,3,1,2,2,3),那么最后一个操作符应该继续放弃最后一个材料,直到没有所有材料出现两次(例如1,3,1,2,2,1)?
这个能行吗?如果我有10个操作符与3个工具和3个材料。任何建议都会有帮助。
发布于 2017-10-28 16:33:35
所以它的工作原理是,一个操作符会使用其中的一个工具,然后是第二个工具。如果第二个没有的话。然后,它也会释放第一个工具(它将把第一个工具放回去,并使其免费并可供其他运营商使用)。这样,等待该工具的另一个操作符就会拿走它,死锁就不会发生了。
int toolx=0; // operator has no tool x
int tooly=0; // operator has no tool y
pthread_mutex_lock(&tool_mutex);
// loop if toolx and tooly are not aquired
while ((toolx + tooly)!=2){
//drop tool x
if (toolx == 1) {
toolbox[mat_x] ++;
toolx -- ;
pthread_cond_signal(&cond_tool);
}
// drop tool y
if (tooly == 1) {
toolbox[mat_y] ++;
tooly -- ;
pthread_cond_signal(&cond_tool);
}
// wait on tool x
while (toolbox[mat_x] == 0) {
pthread_cond_wait (&cond_tool,&tool_mutex); // wait
}
// wait complete and take tool x
toolbox[mat_x] --;
toolx ++ ;
//try take tool y
while (toolbox[mat_y]== 0) { // if other is taking tool y
if (toolx == 1) { //if operator is holding toolx.
toolbox[mat_x] ++;
toolx -- ; // put back tool x
pthread_cond_signal(&cond_tool);
}
pthread_cond_wait (&cond_tool,&tool_mutex); // wait on tools
}
// take tool y
toolbox[mat_y] --;
tooly ++;
}
pthread_mutex_unlock(&tool_mutex);https://stackoverflow.com/questions/46965291
复制相似问题