1
votes

I cannot get out from this deadlock. First let me explain by words what I want to achieve:

  1. Main creates a thread and waits until the thread finishes for the first time
  2. Thread acquires the lock reads from a source as much as he can, (fills buffers and marks them as full), releases the lock only when all buffer are full and at the end he notifies to the main that buffers are all full
  3. Main acquires the lock and consumes 2 buffers, at the end marks them as free to be filled and wakes up the thread again releasing the lock and so on. (there is an object(array+bool), with the array I represent the buffer and with the boolean variable main/thread marks buffer as empty/full). What I did is this (implemented in c++):

    mutex m; //mutex and condition variable are global variables
    condition_variable cv;
    
    void func_executed_by_thread(params){
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk);
        //put stuff inside buffers
        //mark buffer as full
        lk.unlock();
        cv.notify_one();
    }
    
    int main(int argc, char**argv){
        //allocating space for buffer
         std::thread worker(func_executed_by_thread,params);
        while(true){
            std::unique_lock<std::mutex> lk(m);
            cv.wait(lk);
            //get two buffer to consume
            //consume two buffer
            //mark these two buffer as empty
            lk.unlock();
            cv.notify_one();
            //do some other stuff that takes long time (but in the meanwhile the other thread should empty the other buffer)
    
        }
    

    }

the problem is that the thread works only for the first time, then the main consumes 2 buffers, thread never acquires the lock again and the infinite while(true) loop is locked.

1
Do not ever call wait on a condition variable without first checking that the thing you are waiting for hasn't already happened. (That's the reason you acquire the lock before calling wait.)David Schwartz

1 Answers

1
votes

From looking at your code, the function func_executed_by_thread() only gets called once. Either you'll have to create multiple threads inside the while(true) or have func_executed_by_thread() contain a loop as well.