首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多个操作符共享3种工具,如何避免死锁?

多个操作符共享3种工具,如何避免死锁?
EN

Stack Overflow用户
提问于 2017-10-26 23:25:44
回答 1查看 23关注 0票数 0

我想提出一些解决这一僵局的建议:

代码语言:javascript
复制
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

可能会出现僵局:

代码语言:javascript
复制
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个材料。任何建议都会有帮助。

EN

回答 1

Stack Overflow用户

发布于 2017-10-28 16:33:35

所以它的工作原理是,一个操作符会使用其中的一个工具,然后是第二个工具。如果第二个没有的话。然后,它也会释放第一个工具(它将把第一个工具放回去,并使其免费并可供其他运营商使用)。这样,等待该工具的另一个操作符就会拿走它,死锁就不会发生了。

代码语言:javascript
复制
    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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46965291

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档