C++ C++;线程:join到底做什么?
以下代码来自C++ C++;线程:join到底做什么?,c++,multithreading,join,C++,Multithreading,Join,以下代码来自Dash的std::thread示例 #include <iostream> #include <thread> #include <chrono> void foo() { // simulate expensive operation std::this_thread::sleep_for(std::chrono::seconds(1)); } void bar() { // simulate expensive o
Dash
的std::thread
示例
#include <iostream>
#include <thread>
#include <chrono>
void foo()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void bar()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
std::cout << "starting first helper...\n";
std::thread helper1(foo);
std::cout << "starting second helper...\n";
std::thread helper2(bar);
std::cout << "waiting for helpers to finish..." << std::endl;
helper1.join();
// std::cout << "after join... \n";
helper2.join();
std::cout << "done!\n";
}
让我困惑的是:为什么这两种方法有相同的效果?
join
到底做什么?两个线程同时启动并以相同的长度执行。因此,在您的情况下,连接
没有多大作用-两个线程同时开始,同时结束
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void foo()
{
// simulate expensive operation
cout << "Foo Start" << endl;
this_thread::sleep_for(chrono::seconds(1));
cout << "Foo Stop" << endl;
}
void bar()
{
// simulate expensive operation
cout << "Bar Start" << endl;
this_thread::sleep_for(chrono::seconds(2));
cout << "Bar Stop" << endl;
}
int main()
{
thread helper1(foo);
thread helper2(bar);
helper1.join();
cout << "Joined Foo... \n";
helper2.join();
cout << "Joined Bar... \n";
}
#包括
#包括
#包括
使用名称空间std;
void foo()
{
//模拟昂贵的操作
coutJoin阻塞当前线程,这意味着它将不会继续运行,直到调用Join的线程完成。辅助线程在构造函数调用时开始运行。
例如,主线程将停止其执行,直到线程a完成其运行,然后主线程将恢复执行。在一句话中,加入者将等待被加入者完成其执行。我将举一个例子来说明加入
的作用和用途。假设我有大量的计算o do,我想用多个线程并行处理它们,以利用我拥有的多个CPU核
让我们调用从main
开始的线程。假设我有四个内核,所以我将使用四个线程。从线程main
我创建四个新的“工作”线程,并给它们所有B
的子集进行处理
我现在有5个正在运行的线程。但是在我的main
线程中,我想使用计算结果,所以我必须等待其他线程完成。这是通过join
完成的,通过对四个线程逐个调用join
,我确保它们都完成了计算,这样我就可以安全地读取和使用结果ts
通过在四个工作线程中的一个上从main
调用join
,我正在使main
等待该工作线程。因此main
将在等待时停止,这是一个“阻塞调用”
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void foo()
{
// simulate expensive operation
cout << "Foo Start" << endl;
this_thread::sleep_for(chrono::seconds(1));
cout << "Foo Stop" << endl;
}
void bar()
{
// simulate expensive operation
cout << "Bar Start" << endl;
this_thread::sleep_for(chrono::seconds(2));
cout << "Bar Stop" << endl;
}
int main()
{
thread helper1(foo);
thread helper2(bar);
helper1.join();
cout << "Joined Foo... \n";
helper2.join();
cout << "Joined Bar... \n";
}