Why does this simple threaded C++ program crash upon exit unless I call thread.join()? - c++

The program below will end up failing with a message regarding abort() being called.
I'm starting a thread that simple prints to cout. If I use std::this_thread::sleep_for(), I get the error. If I remove this, I get the error. If I call join() on the thread, everything works fine.
Shouldn't the thread have terminated long before the 1000 ms delay was up? Why is this causing an error? I can't believe calling join() is a requirement for a thread.
#include <thread>
#include <iostream>
class ThreadTest
{
public:
ThreadTest() : _t{ &ThreadTest::Run, this } {}
void Wait() { _t.join(); }
private:
void Run(){
std::cout << "In thread" << std::endl;
}
std::thread _t;
};
int main(int argc, char *argv[])
{
ThreadTest tt;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// tt.Wait();
return 0;
}

According to cppreference on thread class destructor :
~thread(): Destroys the thread object. If *this still has an associated running thread (i.e. joinable() == true), std::terminate() is called.
And joinable() :
[...] A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.
So you have to call join() explicitely before your thread variable is automatically destroyed or use the detach() member function.

Check cppreference's std::thread page.
A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.
[the destructor] Destroys the thread object. If *this still has an associated running thread (i.e. joinable() == true), std::terminate() is called.
To get the behavior you want, you'd need to call _t.detach() before exiting from main:
[detach()] Separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits.
After calling detach *this no longer owns any thread.

Related

Why my program is terminated but main thread is run?

I run thread in Qmainwindow using thread library not qthread
I not use thread.join but main thread is run but program is terminated
why program is temianted?
void MainWindow::onSendMsg()
{
// std::thread trdSend([this](){
socket = new QTcpSocket(this);
socket->connectToHost(clientIP,clientPort.toUInt());
//socket->close();
QLabel *lblMsg = new QLabel;
QByteArray data;
qDebug()<<"New Message";
if(filePath.isNull() || filePath.isEmpty())
{
qDebug()<<"Message is Text";
QString msg=leMsg->text();
qDebug()<<"Message : "<< msg;
data =msg.toUtf8();
data.insert(0,'0');
qDebug()<<"Add Flag To Message";
//lblMsg->setText(msg);
qDebug()<<"Message Is Ready";
socket->write(data);
std::thread trdSend((Send()),&data);
//trdSend.join();
emit addWidget(true,true,data);
}
Literally from std::thread::~thread:
~thread(); (since C++11)
Destroys the thread object.
If *this has an associated thread (joinable() == true), std::terminate() is called.
Notes
A thread object does not have an associated thread (and is safe to destroy) after
it was default-constructed
it was moved from
join() has been called
detach() has been called
The instance std::thread trdSend; is created as local variable.
After the emit addWidget(true,true,data); the scope is left and the trdSend is destroyed while none of the four conditions is met.
The std::thread trdSend leaves scope so its destructor is called without thread being joined. So it is still joinable. Therefore the program is required to terminate.
It terminates because what your code does is programming error. It is made that way because we want either:
work thread to send our main program some kind of signal about if it succeeded or failed and so our program knows that the work is done and thread can be joined.
our main thread to wait in join until work is done.
detach the thread as we don't really care how it went. But that is odd so we have to be explicit there.

Std thread detach

Having this simple example:
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
void new_thread(int n) {
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "New thread - exiting!\n";
}
int main() {
std::thread (new_thread, 5).detach();
std::cout << "Main thread - exiting!\n";
return 0;
}
Is it possible for the new_thread not to be automatically terminated by the main thread and to do it's work - outputs New thread - exiting! after 5 secs?
I'm NOT mean the case of join when the main thread waits for a child, but for the main thread to detach the spawned thread and terminates leaving the new thread doing it's work?
Calling detach on a thread means that you don't care about what the thread does any more. If that thread doesn't finish executing before the program ends (when main returns), then you won't see its effects.
However, if the calling thread is around long enough for the detached thread to complete, then you will see the output. Demo.
[basic.start.main]/5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control flows off the end of the compound-statement of main, the effect is equivalent to a return with operand 0.
[support.start.term]/9
[[noreturn]] void exit(int status);
Effects:
...
Finally, control is returned to the host environment.
You seem to expect that when main returns, the program waits for all threads to finish - in effect, implicitly joins all detached threads. That's not what happens - instead, the program terminates, and the operating system cleans up resources allocated to the process (including any threads).
detach separates your thread from the main thread. You want to use join()
Separates the thread of execution from the thread object, allowing
execution to continue independently. Any allocated resources will be
freed once the thread exits.
After calling detach *this no longer owns any thread.
From ref

std::thread thread spun off in object, when does it terminate?

If I spin off an std::thread in the constructor of Bar when does it stop running? Is it guaranteed to stop when the Bar instance gets destructed?
class Bar {
public:
Bar() : thread(&Bar:foo, this) {
}
...
void foo() {
while (true) {//do stuff//}
}
private:
std::thread thread;
};
EDIT: How do I correctly terminate the std::thread in the destructor?
If I spin off an std::thread in the constructor of Bar when does it
stop running?
the thread will run as long as it executing the callable you provided it, or the program terminates.
Is it guaranteed to stop when the Bar instance gets destructed?
No. In order to guarantee that, call std::thread::join in Bar destructor.
Actually, if you hadn't call thread::join or thread::detach prior to Bar::~Bar, than your application will be terminated by calling automatically to std::terminate. so you must call either join (preferable) or detach (less recommended).
you also want to call therad::join on the object destructor because the spawned thread relies on the object to be alive, if the object is destructed while your thread is working on that object - you are using destructed object and you will have undefined behavior in your code.
Short answer: Yes and no. Yes, the thread ends, but not by the usual way (killing the thread), but by the main thread exiting due to a std::terminate call.
Long answer: The thread can only be safely destructed when the underlying function (thread) has finished executing. This can be done in 2 ways
calling join(), which waits for the thread to finish (in your case, never)
calling detach(), which detaches the thread from the main thread (in this case, the thread will end when the main thread closes - when the program terminates).
If the destructor is called if all of those conditions don't apply, then std::terminate is called:
it was default-constructed
it was moved from
join() has been called
detach() has been called
The C++ threading facilities do not include a built-in mechanism for terminating a thread. Instead, you must decide for yourself: a) a mechanism to signal the thread that it should terminate, b) that you do not care about the thread being aborted mid-operation when the process terminates and the OS simply ceases to run it's threads any more.
The std::thread object is not the thread itself but an opaque object containing a descriptor/handle for the thread, so in theory it could be destroyed without affecting the thread, and there were arguments for and against automatic termination of the thread itself. Instead, as a compromise, it was made so that destroying a std::thread object while the thread remained running and attached would cause the application to terminate.
As a result, In it's destructor there is some code like this:
~thread() {
if (this->joinable())
std::terminate(...);
}
Here's an example of using a simple atomic variable and checking for it in the thread. For more complex cases you may need to consider a condition_variable or other more sophisticated signaling mechanism.
#include <thread>
#include <atomic>
#include <chrono>
#include <iostream>
class S {
std::atomic<bool> running_;
std::thread thread_;
public:
S() : running_(true), thread_([this] () { work(); }) {}
void cancel() { running_ = false; }
~S() {
if ( running_ )
cancel();
if ( thread_.joinable() )
thread_.join();
}
private:
void work() {
while ( running_ ) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "tick ...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "... tock\n";
}
std::cout << "!running\n";
}
};
int main()
{
std::cout << "main()\n";
{
S s;
std::this_thread::sleep_for(std::chrono::milliseconds(2750));
std::cout << "end of main, should see a tock and then end\n";
}
std::cout << "finished\n";
}
Live demo: http://coliru.stacked-crooked.com/a/3b179f0f9f8bc2e1

std::thread::detach causes crash after original caller is destroyed

struct Test {
bool active{true};
void threadedUpdate() {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
if(!active) // crashes here after Test instance is destroyed
return;
}
Test() {
std::thread([this]{ while(true) threadedUpdate(); }).detach();
}
~Test() {
// somehow stop the detached thread?
}
};
When an instance of Test is initialized, it spawns and detaches an std::thread which runs in background. When the same instance is destroyed, the previously mentioned thread tries to access the active member, which was destroyed along with the instance, causing a crash (and an AddressSanitizer backtrace).
Is there a way to stop the detached thread on ~Test()?
The design is bad. How should a thread running in background until the caller is destroyed be spawned/handled correctly?
Make the thread a member of the class, and instead of detaching it in the constructor, join it in the destructor. To stop the thread from looping, you can have a boolean inside the class that signals whether the thread should continue running or not (std::atomic<bool> update).
The thread could be executing this: [this] { while (update) threadUpdate(); }.
In the destructor of your class, do update = false, and call thread.join()
You can't stop detached threads. That's the point of .detach() - you don't have any way to refer to the detached thread anymore, at least as far as the C++ standard specifies. If you want to keep a handle to the thread, store the std::thread and call .join() in the destructor.

What happens when calling the destructor of a thread object that has a condition variable waiting?

I am using a SynchronisedQueue to communicate between threads. I found that destroying the thread object when the attaching thread is waiting on a condition variable would cause the program crash. This can be corrected by calling detach() before the thread destruction. But I am wondering what happens exactly when a thread waiting a conditional variable got terminated. Is there another way to use condition variable to avoid this?
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
template <typename Type> class SynchronisedQueue {
public:
void Enqueue(Type const & data) {
std::unique_lock<std::mutex> lock(mutex_);
queue_.push(data);
condition_.notify_one();
}
Type Dequeue() {
std::unique_lock<std::mutex> lock(mutex_);
while (queue_.empty())
condition_.wait(lock);
Type result = queue_.front();
queue_.pop();
return result;
}
private:
std::queue<Type> queue_;
std::mutex mutex_;
std::condition_variable condition_;
};
class Worker {
public:
Worker(SynchronisedQueue<int> * queue) : queue_(queue) {}
void operator()() {
queue_->Dequeue(); // <-- The thread waits here.
}
private:
SynchronisedQueue<int> * queue_;
};
int main() {
auto queue = new SynchronisedQueue<int>();
Worker worker(queue);
std::thread worker_thread(worker);
worker_thread.~thread(); // <-- Crashes the program.
return 0;
}
From the C++11 spec:
30.3.1.3 thread destructor [thread.thread.destr] ~thread();
If joinable(), calls std::terminate(). Otherwise, has no effects.
[ Note: Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the pro grammer must ensure that the destructor is never executed while the thread is still joinable. — end note ]
So calling a thread destructor without first calling join (to wait for it to finish) or detach is guarenteed to immediately call std::terminate and end the program.
The destructor for std::thread will call std::terminate if it is run on a thread if you not have called join() (to wait the thread to finish) or detach() (to detach the thread from the object) on it.
Your code calls the destructor for worker_thread without calling join() or detach() on it, and so std::terminate is called. This is unrelated to the presence of condition variables.
You cannot, ever, destroy a resource while something is, or might be, using it. That's really just common sense.