条件变量,互斥体和锁之间的差异 [英] Differences between Conditional variables, Mutexes and Locks

查看:317
本文介绍了条件变量,互斥体和锁之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如, c ++ 0x接口

我很难知道什么时候使用这些东西(cv,互斥和锁)。
任何人都可以解释或指向某个资源吗?

I am having a hard time figuring out when to use which of these things (cv, mutex and lock). Can anyone please explain or point to a resource?

感谢。

推荐答案

在您引用的页面上,mutex是实际的低级同步基元。你可以取一个互斥体,然后释放它,只有一个线程可以在任何单一时间(因此它是一个同步原语)。递归互斥是可以由同一个线程多次采用的递归互斥,然后它需要被同一个线程释放多次,然后其他人才能接受。

On the page you refer to, "mutex" is the actual low-level synchronizing primitive. You can take a mutex and then release it, and only one thread can take it at any single time (hence it is a synchronizing primitive). A recursive mutex is one which can be taken by the same thread multiple times, and then it needs to be released as many times by the same thread before others can take it.

lock这里只是一个C ++包装类,在其构造函数中使用互斥体,并在析构函数中释放它。

A "lock" here is just a C++ wrapper class that takes a mutex in its constructor and releases it at the destructor. It is useful for establishing synchronizing for C++ scopes.

条件变量是一种更高级/高级的同步原语形式,它将锁与信号机制结合起来。当线程需要等待资源可用时使用。线程可以等待CV,然后资源生产者可以发信号变量,在这种情况下,等待CV的线程得到通知并可以继续执行。互斥体与CV组合以避免竞争条件,其中线程开始在CV上等待,同时另一个线程想要发信号通知;那么不能控制信号是传送还是丢失。

A condition variable is a more advanced / high-level form of synchronizing primitive which combines a lock with a "signaling" mechanism. It is used when threads need to wait for a resource to become available. A thread can "wait" on a CV and then the resource producer can "signal" the variable, in which case the threads who wait for the CV get notified and can continue execution. A mutex is combined with CV to avoid the race condition where a thread starts to wait on a CV at the same time another thread wants to signal it; then it is not controllable whether the signal is delivered or gets lost.

这篇关于条件变量,互斥体和锁之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆