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;
}
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.