I Want to Kill a Std::Thread Using Its Thread Object

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.

Telling an std::thread to kill/stop itself when a condition is met

The call to std::thread::yield() is unrequired and does not kill the calling thread:

Provides a hint to the implementation to reschedule the execution of threads, allowing other threads to run.

Just exit the function to exit the thread.

Note that the use of bRetired is incorrect as two threads can be accessing the same memory location and one of those threads is modifying it: this is undefined behaviour. Also, the change made in the function retire(), a different thread, will not be seen by the thread executing run(): use atomic<bool> for atomicity and visibility.

If join() was used within the constructor the constructor would not return until the thread exited, which would never happen as it would be impossible to call retire() because the object would not be available (as the constructor would not have returned). If it is required to synchronize with the exiting of the thread then do not detach() but join() in the retire() function:

void retire() {
bRetired = true;
tWorker.join();
}

Use RAII for acquiring mutexes (std::lock_guard for example) to ensure it always released. The mutex will be destroyed when it goes out of scope, in this case when its containing class is destructed.

How to Destroy a thread object

You don't have to do anything special.

std::thread gets a callable as a parameter in its constructor and that callable is the function the thread runs.

If that callable ends at some point, a detached thread can clean itself up.
just make sure to

  • exit from the client-handling-function when the client disconnect
  • detach the thread

A simplistic design can be similar to this:

while(server.is_on()){
auto client = server.acccept_client();
std::thread thread([client = std::move(client)]{
handle_client_until_disconnection(client);
});
thread.detach();
}

another approach is to use a thread-pool. that thread-pool is constructed when the application goes up, and destroyed when application exits.

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;

C++ Kill a Thread In Destructor

If you want a thread to die, you should ask it to exit. It's the only reliable way to do it cleanly.

Just change

while (true)

to

while(this->keepRunning)

and synchronize it appropriately. Either don't detach the thread (so the destructor can join it) or add some way for the thread to indicate that it has exited (so the destructor can wait for it).

Oh, and instead of spinning, the thread should probably sleep. In that case, if you don't want the destructor to also block, you need some way to interrupt the sleep: using a timed wait on a condition variable for your sleep makes this easy.

Get a std::thread to detach and terminate itself

Yes, if you have all thread objects stored, you can find the one which thread::id is equal to this_thread::get_id(), and you can call detach() on it, and destroy the thread object after that (the C++11 standard does not prevent that, and I believe it is based on the common practice). Make sure that no other execution thread accesses the instance of std::thread which is destroyed.

But you cannot call join() from the thread itself: an attempt for a thread to join with itself would result in a deadlock, and C++11 implementations should recognize that and throw system_error with the error condition of resource_deadlock_would_occur.

Alternatively, you can leave a message (e.g. via an std::atomic variable) to the main thread that the thread associated with a particular instance of std::thread is about to complete its execution, and let the main thread join with this instance at a later point.



Related Topics



Leave a reply



Submit