0

I want to understand how to work with std::thread. Most of std::thread tutorials looks like that

void foo() { ... }
....
std::thread thread(foo);
....
thread.join();

Ok, I understand that we can specify which function attached to thread in constructor. But, do we have any other way?

In other words, what I need to insert to run t3 thread?

#include <thread>
#include <iostream>

void print(const char* s){
    while (true)
        std::cout << s <<'\n';
}

int main() {

    std::thread t1(print, "foo");
    std::thread *t2;
    t2 = new std::thread(print, "bar");
    std::thread t3; // Don't change this line
    // what I need to put here to run t3 ?

    t1.join();
    t2->join();
    t3.join();
    delete t2;
    return 0;
}

1 Answer 1

3

t3 is essentially a dummy thread. Looking at the reference the default constructor says:

Creates new thread object which does not represent a thread.

But since std::thread has operator=(std::thread&&) you can make it represent an actual thread by moving a new thread into the variable:

t3 = std::thread(print, "foobar");

This will create and launch a new thread, then assign it to t3.

Sign up to request clarification or add additional context in comments.

2 Comments

And what actual difference between "use" or "don't use" std::move in this case?
Actually it is redundant. But I was looking at the documentation and tried to avoid invoking the copy constructor, so I just put in the std::move to be safe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.