Reputation: 187
Basically I am trying to run 2 pieces of code concurrently without freezing eachother, and one of the requires some delay. so, initial code looks like this:
int main() {
cout << "Hello World!";
std::this_thread::sleep_for(std::chrono::milliseconds(166)); // this freezes the whole program for 166 ms
// do other things
}
i have figured a way with threads:
void ThreadFunction() {
cout << "Hello World!";
std::this_thread::sleep_for(std::chrono::milliseconds(166));
}
int main() {
std::thread t1(ThreadFunction);
t1.detach();
// do other things while also doing what the thread t1 does without waiting 166ms
}
This is not exactly my code, but i am trying to recreate code that works as an example.
Threads work fine, but i hear people saying thread.detach()
is not good.
So what are the alternatives?
Upvotes: 2
Views: 251
Reputation: 3950
For C++20 you can also use std::jthread
The difference to std::thread is that it will auto join on destruction, thus the code reduces to:
int main() {
std::jthread t1(ThreadFunction);
// do other things while also doing what the thread t1 does without waiting 166ms
// t1.join() will be called automatically when the current scope exits
}
Upvotes: 1
Reputation: 122133
Your second example seems to be what you want. If you do not want to detach the thread, then don't do it. However, then you must join
it and you can only join
a thread when it finishes its work at some point.
For this simple example I suggest the following (otherwise you need a condition variable or similar to signal the thread that it should stop):
void ThreadFunction() {
for (int i=0; i <100; ++i) {
cout << "Hello World!";
std::this_thread::sleep_for(std::chrono::milliseconds(166));
}
}
int main() {
std::thread t1(ThreadFunction);
// do other things while also doing what the thread t1 does without waiting 166ms
t1.join(); // blocks until ThreadFunction returns
}
Upvotes: 2