0

I would like to ask some suggestions to solve this particular deadlock:

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

A deadlock may happen:

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

None of the operator can acquire both tools, what should the operator do?

Proposal

Create a global variable to record the recent 6 materials taken by the operators. If each material appeared twice (example [1,3,1,2,2,3]), then the last operator should keep abandoning the last material until no all materials appear twice (example [1,3,1,2,2,1])?

Will this work? what if I have 10 operators with 3 tools and 3 materials. Any suggestion will help.

Di Wang
  • 471
  • 1
  • 8
  • 22

1 Answers1

0

So how it works is that an operator would take one of the tools, and then the second one. if the second one wasn't available. then it would let the first one go too ( it will put the first tool back and make it free and available for other operators). This way, the other operator that is waiting for that tool would take it and the deadlock won't happen.

    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);
Di Wang
  • 471
  • 1
  • 8
  • 22