Reputation: 11
I cannot get out from this deadlock. First let me explain by words what I want to achieve:
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.
Upvotes: 1
Views: 427
Reputation: 76
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.
Upvotes: 1