gpt4 book ai didi

c++ - std::thread 在我调用 join() 之前是否运行?

转载 作者:行者123 更新时间:2023-11-30 02:26:51 26 4
gpt4 key购买 nike

在我实例化 std::thread 之后它会开始运行吗?或者线程是否仅在我调用 join() 时才开始运行?这在文档中有点不清楚。

最佳答案

它会在您实例化时执行。

Joining 用于让当前线程等待直到您的其他线程完成执行。

来自 http://en.cppreference.com/w/cpp/thread/thread/thread 的一些示例代码

    void f1(int n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 1 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}

void f2(int& n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 2 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}

int main()
{
int n = 0;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n + 1); // pass by value
std::thread t3(f2, std::ref(n)); // pass by reference
std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
t2.join();
t4.join();
std::cout << "Final value of n is " << n << '\n';
}

Possible output:
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 2 executing
Thread 1 executing
Final value of n is 5

关于c++ - std::thread 在我调用 join() 之前是否运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42358141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com