c++ - 使用 std::condition_variable 同步调用函数
问题描述
我再次沉迷于学习并发并试图解决这个问题。
简而言之,我有一个类和 3 个函数。我需要同步他们的通话(需要打印FirstSecondThird
)。
使用下面的代码会更清楚:
std::function<void()> printFirst = []() { std::cout << "First"; };
std::function<void()> printSecond = []() { std::cout << "Second"; };
std::function<void()> printThird = []() { std::cout << "Third"; };
class Foo {
std::condition_variable cv;
bool mfirst,msecond;
std::mutex mtx;
public:
Foo() {
mfirst = false;
msecond = false;
}
void first(std::function<void()> printFirst) {
std::unique_lock<std::mutex> l(mtx);
printFirst();
mfirst = true;
}
void second(std::function<void()> printSecond) {
std::unique_lock<std::mutex> l(mtx);
cv.wait(l, [this]{return mfirst == true; });
printSecond();
msecond = true;
}
void third(std::function<void()> printThird) {
std::unique_lock<std::mutex> l(mtx);
cv.wait(l, [this] {return (mfirst && msecond) == true; });
printThird();
}
};
int main()
{
Foo t;
std::thread t3((&Foo::third, t, printThird));
std::thread t2((&Foo::second, t, printSecond));
std::thread t1((&Foo::first, t, printFirst));
t3.join();
t2.join();
t1.join();
return 0;
}
猜猜我的输出是什么?它打印ThirdSecondFirst
。
这怎么可能?这段代码是不是容易出现死锁?我的意思是,当第一个线程在函数中获取互斥锁时second
,它不会永远等待,因为现在获取互斥锁我们无法更改变量mfirst
?
解决方案
你有一个非常微妙的错误。
std::thread t3((&Foo::third, t, printThird));
这条线不符合您的预期。它仅使用一个参数 初始化一个线程printThird
,而不是使用您指定的 3 个参数进行初始化。那是因为您不小心使用了逗号表达式。结果,&Foo::third
andt
就被丢弃了,甚至从未调用过成员函数。
在您的代码中调用的唯一函数是printFirst
、printSecond
和printThird
。如果没有任何同步,它们可能会以任意顺序打印。您甚至可以获得交错输出。
std::thread t3{&Foo::third, t, printThird};
这是更正的版本。花括号是为了避免编译器将其视为函数声明,因为大多数令人烦恼的解析
作为旁注,如评论中所述,您使用错误的条件变量。
推荐阅读
- bluetooth - 我可以使用蓝牙 4.0 设备知道蓝牙 5.1 信标的位置吗?
- graphql - 在 GraphQL 中,您可以更改别名中的输出结构吗?
- docker - 如何在 docker-compose 中使用 docker 容器选项
- reactjs - 蚂蚁设计
创建表单的静态数组 - ios - 终止应用程序后将图像保存在 NSCache 中
- angular - Ng2 Smart Table 设置过滤器列表中的选定项
- tensorflow - 如何使用 Keras 获取 val_loss 和 val_acc 指标
- javascript - 运行进度条,每个循环的时间间隔都在变化
- javascript - 通过 SVG 元素上的 onclick 函数重定向到其他 HTML
- android - Android 通过 CallScreeningService 阻止的呼叫有时会响铃