我想正确地同步不同的线程,但到目前为止我只能编写一个不优雅的解决方案。有人可以指出我如何改进以下代码吗?
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();
};
程序的要点由函数thread
描述。该函数由两个 std::thread
执行。该函数接受两个长时间运行的函数 func1
和 func2
以及两个整数引用作为参数。 线程应该只在所有线程退出 func1
后调用 func2
。参数 has_finished
用于协调不同的线程:进入函数后,has_arguments
为零。然后每个 std::thread
递减该值并调用长时间运行的函数 func1
。在离开 func1
之后,has_finished
再次递增。只要该值不是其原始值零,线程就会等待。然后,每个线程都在 func2
上工作。主要功能显示在最后。
如何更好地协调两个线程?我正在考虑使用 std::mutex
和 std::condition_variable
但不知道如何正确使用它们?有人知道我如何改进程序吗?
最佳答案
不要自己写。这种同步被称为“锁存器”(或更一般地称为“屏障”,它可以通过各种库和 C++ 并发 TS 获得。(它也可能以某种形式进入 C++20。)
例如,使用 a version from 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();
}
关于c++ - 如何正确同步这两个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58102763/