When is a condition variable needed, isn't a mutex enough?

前端 未结 6 1226
忘掉有多难
忘掉有多难 2020-11-30 19:06

I\'m sure mutex isn\'t enough that\'s the reason the concept of condition variables exist; but it beats me and I\'m not able to convince myself with a concrete scenario when

6条回答
  •  盖世英雄少女心
    2020-11-30 19:58

    Mutex is for exclusive access of shared resources, while conditional variable is about waiting for a condition to be true. People may think they can implement conditional variable without the support of kernel. A common solution one might come up with is the "flag + mutex" is like:

    lock(mutex)
    
    while (!flag) {
        sleep(100);
    }
    
    unlock(mutex)
    
    do_something_on_flag_set();
    

    but it will never work, because you never release the mutex during the waiting, no one else can set the flag in a thread-safe way. This is why we need conditional variable, when you're waiting on a condition variable, the associated mutex is not hold by your thread until it's signaled.

提交回复
热议问题