Question

I have three threads that I want to keep running till in infinite loop. The threads operate on an object that has a state, and each thread executes or sleeps based on state of the object. I want the input thread to keep checking for any new object with state = 1 and keep working on it, or otherwise wait on it.

class myclass{
    int state;

    myclass(){
        this->state = 0;
    }
    void setState(int x){
        // set this->state to x
    }
    int getState(){
        // return this->state
    }
    // stuff
}

void foo1(myclass* ob){
    // stuff
    while(ob->getState() != 0 || ob->getState() != 1)
    {
        // sleep for 500 ms
    }
    ob->setState(1);
}

void foo2(myclass* ob){
    // stuff
    while(ob->getState() != 1)
    {
        // sleep for 500 ms
    }
    ob->setState(2);
}

void foo3(myclass* ob){
    while(ob->getState() != 2)
    {
        // sleep for 500 ms
    }
    // stuff
    ob->setState(1);
}

int main(){
    myclass* ob = new myclass();
    boost::thread input_thread(boost::bind(&foo1, ob));
    boost::thread process_thread(boost::bind(&foo2, ob));
    boost::thread output_thread(boost::bind(&foo3, ob));

    // stuff
    // join all three threads
}

The while loops in foo2 and foo3 work just fine with input and process threads, but while in foo1 makes input thread go on infinite loop even if there are new objects created and passed to be input/processed/output. Note: in my implementation, I use a dynamic memory data structure to create and pass new objects based on real-time data.

My questions:

  • why does this happen?
  • what would be a better alternative of making the threads wait on new objects in infinite loop and operate on them as they arrive? I would like to know any work-around without using mutex to reduce overhead on scaling the system up.
Was it helpful?

Solution

Firstly, your OR condition will always hold true (either 0 on instantiation and not 1 when it is 0 or instantiated). So your while in foo1() is always true. But that issue isn't present with the other whiles.

Using mutex will be the best idea for such a situation. If u want to avoid it at any cost, put the codes in all 3 functions in while(true) loops and replace the currents whiles with ifs (making sure there's no nested whiles).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top