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

时间:2017-02-21 03:31:20

标签: c++ multithreading

我实例化它开始运行的std::thread(即调用工作函数),或者只在我调用join()时才开始运行,这在文档中有点不清楚。

2 个答案:

答案 0 :(得分:2)

它将在您实例化时执行。

使用连接,以便当前线程将等到另一个线程完成执行。

来自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

答案 1 :(得分:1)

创建std::tread后,它处于运行状态,可以执行指令。

无法保证它会在任何给定的时间间隔内完成任何事情,但随着时间间隔变得越来越长,它会做出更接近100%的概率。

通常,生动的设计实际上保证了当你达到十分之几秒的间隔时,所有非等待的线程都会表现出一些活动。

相关问题