• Linux多线程编程的条件变量


    在stackoverflow上看到一关于多线程条件变量的问题,题主问道:什么时候会用到条件变量,mutex还不够吗?有个叫slowjelj的人做了很好的回答,我再看这个哥们其他话题的一些回答,感觉水平好高的。这里把他的回答粘贴一下方便以后查看,原帖在这里:When is a conditional variable needed, isn't a mutex enough?

     

    Even though you can use them in the way you describe, mutexes weren't designed for use as a notification/synchronization mechanism. They are meant to provide mutually exclusive access to a shared resource. Using mutexes to signal a condition is awkward and I suppose would look something like this (where Thread1 is signaled by Thread2):


    Thread1:

    while(1) {
        lock(mutex); // Blocks waiting for notification from Thread2
        ... // do work after notification is received
        unlock(mutex); // Tells Thread2 we are done
    }
    

    Thread2:

    while(1) {
        ... // do the work that precedes notification
        unlock(mutex); // unblocks Thread1
        lock(mutex); // lock the mutex so Thread1 will block again
    }
    


    There are several problems with this:

    1. Thread2 cannot continue to "do the work that precedes notification" until Thread1 has finished with "work after notification". With this design, Thread2 is not even necessary, that is, why not move "work that precedes" and "work after notification" into the same thread since only one can run at a given time!
    2. If Thread2 is not able to preempt Thread1, Thread1 will immediately re-lock the mutex when it repeats the while(1) loop and Thread1 will go about doing the "work after notification" even though there was no notification. This means you must somehow guarantee that Thread2 will lock the mutex before Thread1 does. How do you do that? Maybe force a schedule event by sleeping or by some other OS-specific means but even this is not guaranteed to work depending on timing, your OS, and the scheduling algorithm.

    These two problems aren't minor, in fact, they are both major design flaws and latent bugs. The origin of both of these problems is the requirement that a mutex is locked and unlocked within the same thread. So how do you avoid the above problems? Use condition variables!

    BTW, if your synchronization needs are really simple, you could use a plain old semaphore which avoids the additional complexity of condition variables.

    这里有一篇不错的文章, Linux 的多线程编程的高效开发经验,还穿插比较了Windows下多线程编程的一些经验,值得阅读。

  • 相关阅读:
    Apache Tomcat开机后台启动
    android res文件夹下面的 values-v11 、 values-v14
    view.performClick()触发点击事件
    android Java BASE64编码和解码一:基础
    Android 正则表达式
    Android 中的Json解析工具fastjson 、序列化、反序列化
    Android 5中不同效果的Toast
    Android 中的编码与解码
    Android Http请求框架二:xUtils 框架网络请求
    Android-Universal-Image-Loader 框架使用
  • 原文地址:https://www.cnblogs.com/woshiweige/p/4541408.html
Copyright © 2020-2023  润新知