How to Terminate a Thread in C++11

How do I terminate a thread in C++11?

  1. You could call std::terminate() from any thread and the thread you're referring to will forcefully end.

  2. You could arrange for ~thread() to be executed on the object of the target thread, without a intervening join() nor detach() on that object. This will have the same effect as option 1.

  3. You could design an exception which has a destructor which throws an exception. And then arrange for the target thread to throw this exception when it is to be forcefully terminated. The tricky part on this one is getting the target thread to throw this exception.

Options 1 and 2 don't leak intra-process resources, but they terminate every thread.

Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.

There is no portable way in C++11 (that I'm aware of) to non-cooperatively kill a single thread in a multi-thread program (i.e. without killing all threads). There was no motivation to design such a feature.

A std::thread may have this member function:

native_handle_type native_handle();

You might be able to use this to call an OS-dependent function to do what you want. For example on Apple's OS's, this function exists and native_handle_type is a pthread_t. If you are successful, you are likely to leak resources.

How to stop the thread execution in C++

thread.join() does not cause the thread to terminate, it waits until the thread ends. It's the responsibility of the thread to end its execution, for example by periodically checking for a certain condition, like a flag.

You already have an atomic flag bReading, which appears to cause the thread to exit.

        if (queueInput.empty()) {
mtxQueueInput.unlock();
if (bReading.load())
continue;
else
break; // thread will exit when queue is empty and bReading == false

So all you need is to set bReading = false in the outer thread before calling thread.join().

bReading = false;
reader.join();

Note that bReading.store(false); inside your thread will have no effect.


Note: you don't need to call atomic.load() and atomic.store(), you can just use them in your code, which will call load() and store() implicitly.

Terminate thread c++11 blocked on read

As you can see here the thread is blocked on a read system call. So even if I clear the flag the thread will be still blocked and join call will block forever.

The solution to this is to std::raise a signal such as SIGINT Edit: You need to raise the signal using pthread_kill so that the signal will be handled by the correct thread. As you can read from the manual, read is interrupted by signals. You must handle the std::signal or else the entire process will terminate prematurely.

On systems that use BSD signal handling instead of POSIX, system calls are by default restarted rather than failed upon interrupt. My suggested approach relies on the POSIX behaviour, where the call sets EINTR and returns. The POSIX behaviour can set explicitly using siginterrupt. Another option is to register the signal handler using sigaction, which does not restart, unless specified by a flag.

After read has been interrupted, you must check whether the thread should stop before retrying the read.

using c++11 (maybe even without it) don't call any blocking system call in the thread

Calling blocking system calls is just fine. What you shouldn't do is call uninterruptible system calls that may block indefinitely long time, if you wish to terminate the thread without terminating the process (within finite time). Off the top of my head, I don't know if any system call matches such description.

A minimal example (complete except for indefinitely blocking read. You can use sleep(100000) to simulate it):

#include <thread>
#include <iostream>
#include <csignal>
#include <cerrno>
#include <unistd.h>

constexpr int quit_signal = SIGINT;
thread_local volatile std::sig_atomic_t quit = false;

int main()
{
// enforce POSIX semantics
siginterrupt(quit_signal, true);

// register signal handler
std::signal(quit_signal, [](int) {
quit = true;
});

auto t = std::thread([]() {
char buf[10];
while(!quit) {
std::cout << "initiated read\n";
int count = read(some_fd_that_never_finishes, buf, sizeof buf);
if (count == -1) {
if (errno == EINTR) {
std::cout << "read was interrupted due to a signal.\n";
continue;
}
}
}
std::cout << "quit is true. Exiting\n";;
});

// wait for a while and let the child thread initiate read
sleep(1);

// send signal to thread
pthread_kill(t.native_handle(), quit_signal);

t.join();
}

Forcibly killing a thread is usually a very bad idea, especially in C++, which is probably why std::thread API doesn't provide interface for it.

If you really want to kill a thread of execution - which isn't necessary in this case, since you can safely interrupt the system call instead - then you should use a child process instead of child thread. Killing a child process won't break the heap of the parent process. That said, C++ standard library does not provide an inter-process API.

C++ Killing a std::thread

  1. Is there a way to send a SIGKILL or equivalent to a std::thread to kill it?

There is no such equivalent; at least a standard one.


  1. Is there a way to catch this signal from within the thread to clean up resources?

There is no standard way in C++ to signal a thread.

POSIX has pthread_kill that can be used to signal a thread. Note that "stop", "continue", or "terminate" signals affect the entire process, so this is not for what you're asking exactly.

However, asynchronous signal handlers are limited on what they can do, and resource cleanup won't be possible. What you should do is let the thread know that it should terminate, and let it stop and cleanup voluntarily.

thread that listens for an event.

Solution depends on what kind of listening we are considering. If it is a condition variable, you can set an atomic boolean to request termination and wake up the thread by notifying.

If listening is a blocking system call, solution is a bit trickier. The great thing about raising a signal, is that it interrupts blocking system calls. You can use the handler to set a volatile sig_atomic_t variable that the thread can read and voluntarily return. The interruption may give your thread a chance to check the variable before resuming the wait. The caveat is that we must turn that may into a guarantee:

You must register the signal handler using sigaction (standard POSIX function; not standard C++) with SA_RESTART unset. Otherwise depending on system defaults, the system call might resume instead of returning.


Another approach is to send the event that the other thread is waiting for. This may be simpler or trickier than above depending on what kind of event we are considering. For example, when listening on a socket, it is typically possible to connect to that socket.


There is a proposal to introduce std::jthread thread wrapper into a future C++ standard, which offers a portable way to request a thread to stop. Unfortunately, I don't know what guarantees there would be regarding blocking system calls.

C++11 Kill threads when main() returns?

What happens in an application is not related to what the OS may do.

If a std::thread is destroyed, still having a joinable thread, the application calls std::terminate and that's what is showing up: http://en.cppreference.com/w/cpp/thread/thread/~thread`

With the c++11 threads, either you detach if you do not care on their completion time, or you care and need to join before the thread object is destroyed.

How to terminate a thread safely? (with the usage of pointer) c++

When creating objects with dynamic allocation, you have to deallocate the memory with operator delete so it calls appropriate destructor.

In the first example, two std::thread objects are created. At the end of main function, the destructor std::thread::~thread is called. Since the threads are not joined, the destructor reports an error.

On the other hand, in the second example, you called operator new so you create objects with dynamic allocation. But, you didn't call operator delete, so the destructor is not called. That is, the program didn't check whether the threads are joined.

Therefore, the only way to correctly terminate a thread is to call std::thread::join. If you want to use pointers, you have to do as following:

std::thread *th = new std::thread(foo);
...
th->join();
delete th;

Terminate a thread from outside in C++11

First, don't use raw std::threads. They are rarely a good idea. It is like manually calling new and delete, or messing with raw buffers and length counters in io code -- bugs waiting to happen.

Second, instead of killing the thread, provide the thread task with a function or atomic variable that says when the worker should kill itself.

The worker periodically checks its "should I die" state, and if so, it cleans itself up and dies.

Then simply signal the worker to die, and wait for it to do so.

This does require work in your worker thread, and if it does some task that cannot be interrupted that lasts a long time it doesn't work. Don't do tasks that cannot be interrupted and last a long time.

If you must do such a task, do it in a different process, and marshall the results back and forth. But modern OSs tend to have async APIs you can use instead of synchronous APIs for IO tasks, which lend themselves to being aborted if you are careful.

Terminating a thread while it is in an arbitrary state places your program into an unknown and undefined state of execution. It could be holding a mutex and never let it go in a standard library call, for example. But really, it can do anything at all.

Generally detaching threads is also a bad idea, because unless you magically know they are finished (difficult because you detached them), what happens after main ends is implementation defined.

Keep track of your threads, like you keep track of your memory allocations, but moreso. Use messages to tell threads to kill themselves. Join threads to clean up their resources, possibly using condition variables in a wrapper to make sure you don't join prior to the thread basically being done. Consider using std::async instead of raw threads, and wrap std::async itself up in a further abstraction.

How to terminate a std::thread?

Don't detach the thread. Instead, you can have a data member that hold a pointer to the thread, and join the thread in destructor.

class YourClass {
public:
~YourClass() {
if (_thread != nullptr) {
_thread->join();
delete _thread;
}
}
void mainProcees() {
_thread = new thread(&YourClass::downloadImg,this);
}
private:
thread *_thread = nullptr;
};

UPDATE

Just as @milleniumbug pointed out, you don't need dynamic allocation for the thread object, since it is movable. So the other solution is as follows.

class YourClass {
public:
~YourClass() {
if (_thread.joinable())
_thread.join();
}
void mainProcess() {
_thread = std::thread(&YourClass::downloadImg, this);
}
private:
std::thread _thread;
};


Related Topics



Leave a reply



Submit