等待同一个条件变量时,我们可以使用两个不同的互斥锁吗?

Can we use two different mutex when waiting on same conditional variable?

考虑以下场景:

线程 1

mutexLk1_
gcondVar_.wait(mutexLk1);

线程 2

mutexLk2_
gcondVar_.wait(mutexLk2);

线程 3

condVar_
gcondVar_.notify_all();

我观察到 notify_all() 不会同时唤醒两个线程,而只会唤醒两个线程中的一个。如果我要用 mutexLk1 替换 mutexLk2。我得到一个功能代码。

要重现该问题,请考虑以下 修改后的 示例 cppref

#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>

std::condition_variable cv;
std::mutex cv_m1;
std::mutex cv_m; // This mutex is used for three purposes:
                 // 1) to synchronize accesses to i
                 // 2) to synchronize accesses to std::cerr
                 // 3) for the condition variable cv
int i = 0;

void waits1()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cerr << "Waiting... \n";
    cv.wait(lk, []{return i == 1;});
    std::cerr << "...finished waiting. waits1 i == 1\n";
}

void waits()
{
    std::unique_lock<std::mutex> lk(cv_m1);
    std::cerr << "Waiting... \n";
    cv.wait(lk, []{return i == 1;});
    std::cerr << "...finished waiting. i == 1\n";
}

void signals()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    {
        std::lock_guard<std::mutex> lk(cv_m);
        std::cerr << "Notifying...\n";
    }
    cv.notify_all();

    std::this_thread::sleep_for(std::chrono::seconds(1));

    {
        std::lock_guard<std::mutex> lk(cv_m);
        i = 1;
        std::cerr << "Notifying again...\n";
    }
    cv.notify_all();
}

int main()
{
    std::thread t1(waits), t2(waits1), t3(waits), t4(signals);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
}

编译命令

g++ --std=c++17 t.cpp -lpthread

这里有趣的是,上面的代码在具有 g++ 9.3 版本的 centos 7.9 系统(与 g++ 10 在该系统上的行为相同) ) 但对于 ubuntu 18.04 系统(使用 g++ 9.4),这没有任何问题

知道要遵循的预期行为或理想做法是什么吗?因为在我的用例中,我需要两个不同的互斥体来保护不同的数据结构,但触发器来自相同的条件变量。

谢谢

看来你违反了标准:

33.5.3 Class condition_variable [thread.condition.condvar]

void wait(unique_lock& lock);

Requires: lock.owns_lock() is true and lock.mutex() is locked by the calling thread, and either

(9.1) — no other thread is waiting on this condition_variable object or

(9.2) — lock.mutex() returns the same value for each of the lock arguments supplied by all concurrently waiting (via wait, wait_for, or wait_until) threads.

显然有两个线程正在等待,lock.mutex() 与 return 不同。

为了详细说明我的评论,问题中有三个 项需要同步。

有两个独立的数据块,问题说每个数据块都与两个独立的互斥锁正确同步。没关系,但这无关紧要。

第三个同步问题是确保某些其他指定条件得到满足,以便某些线程 运行。这是用条件变量实现的;到目前为止,一切都很好。但是当多个线程等待一个条件变量时,所有等待的线程必须使用同一个互斥量。所以代码需要一个互斥锁供线程在等待时使用。虽然 可能 可以使用一个或另一个现有的互斥锁来进行同步,但代码似乎更有可能需要另一个互斥锁,专门用于等待该条件变量。

处理同步时,要克制分享管理同步的东西的冲动;这会给你带来麻烦。