Quantcast
Channel: Condition variable spurious wakeup/round robin tasks - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Condition variable spurious wakeup/round robin tasks

0
0

I'm new to C++ threading and I'm trying to write a round robin (cooperative) task manager using C++ threads. Is the declaration of round_robin_task_ulock below valid - it's a global static variable. I want to defer locking the mutex until the task manager thread starts running.

static std::mutex                      round_robin_task_mutex;
static std::condition_variable         task_manager_cvar; 
static thread                          round_robin_task_manager_thread;
static std::unique_lock<std::mutex>    
     round_robin_task_ulock(round_robin_task_mutex, std::defer_lock);

static void round_robin_task_manager()
{
    round_robin_task_ulock.lock();
    //..
}

Once the task manager thread is running it can start a round robin task running with a notify followed by wait

 round_robin_tasks[current_task_id].task_cvar.notify_one();
 // release the mutex and go to sleep
 task_manager_cvar.wait(round_robin_task_ulock); 
 // now we own the mutex again

and when a round robin task wants to suspend itself it notifies the task manager thread

 task_manager_cvar.notify_one();
 round_robin_tasks[current_task_id].task_cvar.wait
                  (round_robin_task_ulock, [] { return  
                      round_robin_tasks[my_task_id].task_running_now; } );

Are there any obvious problems with this? I've read about spurious wake. Is it possible that a spurious wake could wake up the task manager thread while a round robin task still owned the mutex or is it guaranteed that when the wait function returns, the mutex is always owned (locked) by the thread that called wait.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images