fab*_*ian 0 c++ performance multithreading mutex
我想正确同步不同的线程,但到目前为止我只能编写一个不优雅的解决方案。有人可以指出我如何改进以下代码吗?
typedef void (*func)();
void thread(func func1, func func2, int& has_finished, int& id) {
has_finished--;
func1();
has_finished++;
while (has_finished != 0) std::cout << "thread " << id << " waiting\n";
std::cout << "thread" << id << "resuming\n";
func2();
}
int main() {
int has_finished(0), id_one(0), id_two(1);
std::thread t1(thread, fun, fun, std::ref(has_finished), std::ref(id_one));
std::thread t2(thread, fun, fun, std::ref(has_finished), std::ref(id_two));
t1.join();
t2.join();
};
Run Code Online (Sandbox Code Playgroud)
程序的要点由函数描述thread。该函数由两个 s 执行std::thread。该函数接受两个长时间运行的函数func1和func2两个整数引用作为参数。线程应该仅func2在所有线程退出后func1调用。该参数has_finished用于协调不同的线程:进入函数后,has_arguments为零。然后每个函数std::thread都会递减该值并调用长时间运行的函数func1。离开后func1,has_finished再次递增。只要该值不是其原始值零,线程就会等待。然后,每个线程都在 上工作func2。主要功能在最后展示。
如何更好地协调两个线程?我正在考虑使用std::mutexandstd::condition_variable但不知道如何正确使用它们?有人知道我如何改进该程序吗?
不要自己写这个。这种同步被称为“闩锁”(或者更一般地说是“屏障”,它可以通过各种库和 C++ 并发 TS 获得。(它也可能以某种形式进入 C++20。)
例如,使用Boost 的版本:
#include <iostream>
#include <thread>
#include <boost/thread/latch.hpp>
void f(boost::latch& c) {
std::cout << "Doing work in round 1\n";
c.count_down_and_wait();
std::cout << "Doing work in round 2\n";
}
int main() {
boost::latch c(2);
std::thread t1(f, std::ref(c)), t2(f, std::ref(c));
t1.join();
t2.join();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
337 次 |
| 最近记录: |