144

I am getting a C++ error with threading:

terminate called without an active exception
Aborted

Here is the code:

#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>

template<typename TYPE>
class blocking_stream
{
public:
    blocking_stream(size_t max_buffer_size_)
        :   max_buffer_size(max_buffer_size_)   
    {
    }

    //PUSH data into the buffer
    blocking_stream &operator<<(TYPE &other)
    {
        std::unique_lock<std::mutex> mtx_lock(mtx); 
        while(buffer.size()>=max_buffer_size)
            stop_if_full.wait(mtx_lock);

        buffer.push(std::move(other));

        mtx_lock.unlock();
        stop_if_empty.notify_one();
        return *this;
    }
    //POP data out of the buffer 
    blocking_stream &operator>>(TYPE &other)
    {
        std::unique_lock<std::mutex> mtx_lock(mtx);
        while(buffer.empty())
            stop_if_empty.wait(mtx_lock);

        other.swap(buffer.front()); 
        buffer.pop();

        mtx_lock.unlock();
        stop_if_full.notify_one();
        return *this;
    }

private:
    size_t max_buffer_size;
    std::queue<TYPE> buffer;
    std::mutex mtx;
    std::condition_variable stop_if_empty,
                            stop_if_full;
    bool eof;   
};

I modeled my code around this example: http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

What am I doing wrong and how do I fix the error?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
111111
  • 15,686
  • 6
  • 47
  • 62

6 Answers6

187

When a thread object goes out of scope and it is in joinable state, the program is terminated. The Standard Committee had two other options for the destructor of a joinable thread. It could quietly join -- but join might never return if the thread is stuck. Or it could detach the thread (a detached thread is not joinable). However, detached threads are very tricky, since they might survive till the end of the program and mess up the release of resources. So if you don't want to terminate your program, make sure you join (or detach) every thread.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Bartosz Milewski
  • 11,012
  • 5
  • 36
  • 45
  • 3
    "When a thread object goes out of scope and it is in joinable state, the program is terminated" Could you provide a dead simple, reproducible example of this? The example in the OP is a bit complicated. – Alec Jacobson Sep 10 '12 at 18:43
  • 1
    And that statement seems contradictory to this answer: http://stackoverflow.com/a/3970921/148668 – Alec Jacobson Sep 10 '12 at 18:53
  • 7
    @mangledorf: Notice that they are talking aobut boost::thread and I'm talking about std::thread. These two have different destruction behaviours. This was a conscious decision on the part of the Committee. – Bartosz Milewski Sep 20 '12 at 19:54
  • What if you run into this issue with `std::async`? How do you join / detach any thread that may be created there? It doesn't seem like waiting on the resultant future would be enough, because [this says](http://en.cppreference.com/w/cpp/thread/async) the thread could "potentially be from a thread pool", and future's wait() doesn't really imply terminating a thread in a pool (and that wouldn't make sense anyways for sane thread pools). – Jason C Sep 11 '16 at 04:11
  • 2
    Just an update that in C++20, `std::jthread` will call `.join()` in the destructor (as it goes out of scope). Which I personally like better since it follows RAII better. – pooya13 Aug 14 '19 at 20:04
  • 1
    Everytime I run into this, the error message is completely inscrutable until I Google and stumble upon this answer. – Conrad Meyer May 03 '23 at 23:54
70

How to reproduce that error:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() { 
  std::thread t1(task1, "hello"); 
  return 0;
}

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
terminate called without an active exception
Aborted (core dumped)

You get that error because you didn't join or detach your thread.

One way to fix it, join the thread like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() { 
  std::thread t1(task1, "hello"); 
  t1.join();
  return 0;
}

Then compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

The other way to fix it, detach it like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() 
{ 
     {

        std::thread t1(task1, "hello"); 
        t1.detach();

     } //thread handle is destroyed here, as goes out of scope!

     usleep(1000000); //wait so that hello can be printed.
}

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

Read up on detaching C++ threads and joining C++ threads.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
  • 1
    in this context, the use of usleep() makes sense only if thread is detached and the handle has been destroyed (by going out of scope). SO I edited your code to reflect this. – Nawaz Sep 03 '15 at 11:51
  • This doesn't work. I still get the error when I press ctrl+c to interrupt the process, which prevents the join() from completing. – Cerin Dec 24 '20 at 05:43
  • You don't want to have a timer enforce the execution of a detached thread, use a lock. – Yvain Jan 07 '21 at 17:18
22

Eric Leschinski and Bartosz Milewski have given the answer already. Here, I will try to present it in a more beginner friendly manner.

Once a thread has been started within a scope (which itself is running on a thread), one must explicitly ensure one of the following happens before the thread goes out of scope:

  • The runtime exits the scope, only after that thread finishes executing. This is achieved by joining with that thread. Note the language, it is the outer scope that joins with that thread.
  • The runtime leaves the thread to run on its own. So, the program will exit the scope, whether this thread finished executing or not. This thread executes and exits by itself. This is achieved by detaching the thread. This could lead to issues, for example, if the thread refers to variables in that outer scope.

Note, by the time the thread is joined with or detached, it may have well finished executing. Still either of the two operations must be performed explicitly.

Hari
  • 1,561
  • 4
  • 17
  • 26
3

First you define a thread. And if you never call join() or detach() before calling the thread destructor, the program will abort.

As follows, 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.

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 programmer must ensure that the destructor is never executed while the thread is still joinable.

Li Yingjun
  • 604
  • 5
  • 7
1

As long as your program die, then without detach or join of the thread, this error will occur. Without detaching and joining the thread, you should give endless loop after creating thread.

int main(){

std::thread t(thread,1);

while(1){}

//t.detach();
return 0;}

It is also interesting that, after sleeping or looping, thread can be detach or join. Also with this way you do not get this error.

Below example also shows that, third thread can not done his job before main die. But this error can not happen also, as long as you detach somewhere in the code. Third thread sleep for 8 seconds but main will die in 5 seconds.

void thread(int n) {std::this_thread::sleep_for (std::chrono::seconds(n));}

int main() {
std::cout << "Start main\n";
std::thread t(thread,1);
std::thread t2(thread,3);
std::thread t3(thread,8);
sleep(5);

t.detach();
t2.detach();
t3.detach();
return 0;}
1

yes, the thread must be join(). when the main exit

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
yongyu wu
  • 99
  • 1
  • 2
  • 4
    This answer is probably more suited to a comment attached to another answer. And I have to say, welcome to Stack Overflow! – Contango May 02 '20 at 08:40