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

前端 未结 6 1229
忘掉有多难
忘掉有多难 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 20:01

    You need condition variables, to be used with a mutex (each cond.var. belongs to a mutex) to signal changing states (conditions) from one thread to another one. The idea is that a thread can wait till some condition becomes true. Such conditions are program specific (i.e. "queue is empty", "matrix is big", "some resource is almost exhausted", "some computation step has finished" etc). A mutex might have several related condition variables. And you need condition variables because such conditions may not always be expressed as simply as "a mutex is locked" (so you need to broadcast changes in conditions to other threads).

    Read some good posix thread tutorials, e.g. this tutorial or that or that one. Better yet, read a good pthread book. See this question.

    Also read Advanced Unix Programming and Advanced Linux Programming

    P.S. Parallelism and threads are difficult concepts to grasp. Take time to read and experiment and read again.

提交回复
热议问题