Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::thread run before I call join()?

After I instantiate the std::thread does it start running then? Or does a thread only start running when I call join()? This is a bit unclear in the docs.

like image 496
Victor Aurélio Avatar asked Oct 16 '25 22:10

Victor Aurélio


2 Answers

It will execute when you instantiate it.

Joining is used so that the current thread will wait until your other thread finishes execution.

Some example code from 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
like image 75
TFK Avatar answered Oct 19 '25 12:10

TFK


Once a std::tread is created it is in a running state where it can execute instructions.

There is no guarantee that it will do anything at all in any given interval of time, but the probability that it does something goes ever closer to 100% as that interval gets longer and longer.

Usually, design for liveliness practically guarantees that when you get up to intervals of tenths of seconds, all your non-waiting threads will exhibit some activity.

like image 35
Cheers and hth. - Alf Avatar answered Oct 19 '25 13:10

Cheers and hth. - Alf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!