- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在尝试使用 C++11 std::condition_variable,但是当我尝试从第二个线程锁定与其关联的 unique_lock 时,出现异常“已避免资源死锁”。创建它的线程可以锁定和解锁它,但第二个线程不能,尽管我很确定 unique_lock 不应该在第二个线程尝试锁定它时已经锁定。
FWIW 我在 Linux 中使用 gcc 4.8.1 和 -std=gnu++11。
我已经围绕 condition_variable、unique_lock 和 mutex 编写了一个包装器类,因此我的代码中没有任何其他内容可以直接访问它们。注意 std::defer_lock 的使用,我已经掉进了那个陷阱:-)。
class Cond {
private:
std::condition_variable cCond;
std::mutex cMutex;
std::unique_lock<std::mutex> cULock;
public:
Cond() : cULock(cMutex, std::defer_lock)
{}
void wait()
{
std::ostringstream id;
id << std::this_thread::get_id();
H_LOG_D("Cond %p waiting in thread %s", this, id.str().c_str());
cCond.wait(cULock);
H_LOG_D("Cond %p woke up in thread %s", this, id.str().c_str());
}
// Returns false on timeout
bool waitTimeout(unsigned int ms)
{
std::ostringstream id;
id << std::this_thread::get_id();
H_LOG_D("Cond %p waiting (timed) in thread %s", this, id.str().c_str());
bool result = cCond.wait_for(cULock, std::chrono::milliseconds(ms))
== std::cv_status::no_timeout;
H_LOG_D("Cond %p woke up in thread %s", this, id.str().c_str());
return result;
}
void notify()
{
cCond.notify_one();
}
void notifyAll()
{
cCond.notify_all();
}
void lock()
{
std::ostringstream id;
id << std::this_thread::get_id();
H_LOG_D("Locking Cond %p in thread %s", this, id.str().c_str());
cULock.lock();
}
void release()
{
std::ostringstream id;
id << std::this_thread::get_id();
H_LOG_D("Releasing Cond %p in thread %s", this, id.str().c_str());
cULock.unlock();
}
};
我的主线程创建了一个 RenderContext,它有一个与之关联的线程。从主线程的角度来看,它使用 Cond 来通知渲染线程执行某个操作,也可以在 COnd 上等待渲染线程完成该操作。渲染线程在 Cond 上等待主线程发送渲染请求,并在必要时使用相同的 Cond 告诉主线程它已完成一个 Action 。当渲染线程试图锁定 Cond 以检查/等待渲染请求时,我得到的错误发生了,此时它根本不应该被锁定(因为主线程正在等待它),更不用说被同一个线程。这是输出:
DEBUG: Created window
DEBUG: OpenGL 3.0 Mesa 9.1.4, GLSL 1.30
DEBUG: setScreen locking from thread 140564696819520
DEBUG: Locking Cond 0x13ec1e0 in thread 140564696819520
DEBUG: Releasing Cond 0x13ec1e0 in thread 140564696819520
DEBUG: Entering GLFW main loop
DEBUG: requestRender locking from thread 140564696819520
DEBUG: Locking Cond 0x13ec1e0 in thread 140564696819520
DEBUG: requestRender waiting
DEBUG: Cond 0x13ec1e0 waiting in thread 140564696819520
DEBUG: Running thread 'RenderThread' with id 140564575180544
DEBUG: render thread::run locking from thread 140564575180544
DEBUG: Locking Cond 0x13ec1e0 in thread 140564575180544
terminate called after throwing an instance of 'std::system_error'
what(): Resource deadlock avoided
老实说,我不太明白 unique_lock 的用途以及为什么 condition_variable 需要一个而不是直接使用互斥锁,所以这可能是问题的原因。我在网上找不到很好的解释。
最佳答案
前言:了解条件变量的一件重要事情是它们可能会受到随机的、虚假的唤醒。换句话说,CV 可以从 wait()
退出,而无需任何人先调用 notify_*()
。不幸的是,没有办法区分这种虚假的唤醒和合法的唤醒,所以唯一的解决方案是拥有一个额外的资源(至少是一个 bool 值),这样你就可以判断是否真正满足了唤醒条件。
这个额外的资源也应该由互斥锁保护,通常与您用作 CV 的伴侣相同。
CV/mutex 对的典型用法如下:
std::mutex mutex;
std::condition_variable cv;
Resource resource;
void produce() {
// note how the lock only protects the resource, not the notify() call
// in practice this makes little difference, you just get to release the
// lock a bit earlier which slightly improves concurrency
{
std::lock_guard<std::mutex> lock(mutex); // use the lightweight lock_guard
make_ready(resource);
}
// the point is: notify_*() don't require a locked mutex
cv.notify_one(); // or notify_all()
}
void consume() {
std::unique_lock<std::mutex> lock(mutex);
while (!is_ready(resource))
cv.wait(lock);
// note how the lock still protects the resource, in order to exclude other threads
use(resource);
}
与您的代码相比,请注意多个线程如何同时调用 produce()/consume()
而不必担心共享的 unique_lock
:唯一共享的东西是 mutex/cv/resource
并且每个线程都有自己的 unique_lock
,如果互斥量已经被其他东西锁定,则强制线程等待轮到它。
如您所见,资源实际上无法与 CV/mutex 对分开,这就是为什么我在评论中说您的包装类不适合恕我直言,因为它确实试图将它们分开。
通常的方法不是像您尝试的那样为 CV/mutex 对制作包装器,而是为整个 CV/mutex/resource 三重奏。例如。一个线程安全的消息队列,其中消费者线程将等待 CV,直到队列中有消息准备好被消费。
如果您真的只想包装 CV/mutex 对,您应该摆脱不安全的 lock()/release()
方法(来自RAII 的观点)并用返回 unique_ptr
的单个 lock()
方法替换它们:
std::unique_ptr<std::mutex> lock() {
return std::unique_ptr<std::mutex>(cMutex);
}
这样你就可以像我上面展示的那样使用你的Cond
包装类:
Cond cond;
Resource resource;
void produce() {
{
auto lock = cond.lock();
make_ready(resource);
}
cond.notify(); // or notifyAll()
}
void consume() {
auto lock = cond.lock();
while (!is_ready(resource))
cond.wait(lock);
use(resource);
}
但老实说,我不确定这是否值得:如果您想使用 recursive_mutex
而不是普通的 mutex
怎么办?那么,您必须从您的类中制作一个模板,以便您可以选择互斥锁类型(或者完全编写第二个类,是的代码重复)。无论如何,您不会获得太多 yield ,因为您仍然必须编写几乎相同的代码来管理资源。仅用于 CV/mutex 对的包装器类太薄了,恕我直言,它不是真正有用的。但像往常一样,YMMV。
关于linux - 锁定 C++11 std::unique_lock 导致死锁异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17840149/
我正在开发一个小型图书馆,我需要做的一件事是让访问者访问一些数据并返回结果。 在一些较旧的 C++ 代码中,访问者需要声明一个 typedef return_type .例如,boost::stati
我正在尝试使用std:map类型的键和值制作std::any Visual Studio 2017 std::map m("lastname", "Ivanov"); std::cout (m["la
我已经在 C++ 的 map 中声明了一个集合为 std::map> .如何循环访问或打印设定值? 最佳答案 如果你知道如何迭代 std::map或 std::set单独地,您应该可以毫无问题地组合迭
如何循环? 我已经试过了: //----- code std::vector >::iterator it; for ( it = users.begin(); it != users.end();
我有两个用例。 A.我想同步访问两个线程的队列。 B.我想同步两个线程对队列的访问并使用条件变量,因为其中一个线程将等待另一个线程将内容存储到队列中。 对于用例 A,我看到了使用 std::lock_
我正在查看这两种类型特征的文档,但不确定有什么区别。我不是语言律师,但据我所知,它们都适用于“memcpy-able”类型。 它们可以互换使用吗? 最佳答案 不,这些术语不能互换使用。这两个术语都表示
我有以下测试代码,其中有一个参数 fS,它是 ofstream 的容器: #include #include #include #include int
这是这个问题的延续 c++ function ptr in unorderer_map, compile time error 我试图使用 std::function 而不是函数指针,并且只有当函数是
std::unordered_map str_bool_map = { {"a", true}, {"b", false}, {"c", true} }; 我们可以在此映射上使
我有以下对象 std::vector> vectorList; 然后我添加到这个使用 std::vector vec_tmp; vec_tmp.push_back(strDRG); vec_tmp.p
为什么 std::initializer_list不支持std::get<> , std::tuple_size和 std::tuple_element ?在constexpr中用得很多现在的表达式,
我有一个像这样定义的变量 auto drum = std::make_tuple ( std::make_tuple ( 0.3f , Ex
假设我有一个私有(private)std::map在我的类(class)里std::map 。我怎样才能将其转换为std::map返回给用户?我想要下面的原型(prototype) const std
假设我有一个私有(private)std::map在我的类(class)里std::map 。我怎样才能将其转换为std::map返回给用户?我想要下面的原型(prototype) const std
问题 我正在尝试将 lambda 闭包传递给 std::thread,它使用任意封闭参数调用任意封闭函数。 template std::thread timed_thread(Function&& f
我想创建一个模板类,可以容纳容器和容器的任意组合。例如,std::vector或 std::map ,例如。 我尝试了很多组合,但我必须承认模板的复杂性让我不知所措。我编译的关闭是这样的: templ
我有一个 std::vector>我将其分配给相同类型的第二个 vector 。 我收到这个编译器错误: /opt/gcc-8.2.0/include/c++/8.2.0/bits/stl_algob
有时候,我们有一个工厂可以生成一个 std::unique_ptr vector ,后来我们想在类/线程/你命名的之间共享这些指针。因此,最好改用 std::shared_ptr 。当然有一种方法可以
这个问题在这里已经有了答案: Sorting a vector of custom objects (14 个答案) 关闭 6 年前。 我创建了一个 vector vector ,我想根据我定义的参
我有三个类(class)成员: public: std::vector > getObjects(); std::vector > getObjects() const; privat
我是一名优秀的程序员,十分优秀!