How to stop a running parallel thread with C++ on Mac? - c++

I’ve been looking for an answer, and indeed found some possible ways to stop a running parallel thread with C++, but the solutions would usually apply only on Windows (for instance, the TerminateThread() function ). Is there a way to stop a running parallel thread on Mac (I’m using CodeBlocks) ?

A typical clean/safe setup might be....
std::atomic<bool> exit{false};
std::thread thread([&]{
while (!exit) { /* do stuff */ }
});
// later, when you want to exit:
exit = true;
// `join` before the `thread` object goes out of scope
thread.join();
From this you can probably see there are endless ways to tell your thread to stop running and end cleanly. Just make sure whatever you way you use is thread safe (either atomic or protected by a mutex) and make sure you call thread.join() before the thread object goes out of scope, or any time you wish to block waiting for the thread to finish.

Related

How to join a number of threads which don't stop in C++

In C++ I have an std::vector of threads, each running a function running forever [while(true)].
I'm joining them in a for loop:
for (auto& thread : threads)
{
thread.join();
}
When the program finishes I'm getting a std::terminate() call inside the destructor of one of the threads. I think I understand why that happens, except for the first thread the other join calls don't get called.
What is the correct way of joining those threads?
And is it actually necessary to join them? (assuming they are not supposed to join under normal circumstances)
If the threads cannot be joined because they never exit then you could use std::thread::detach (https://en.cppreference.com/w/cpp/thread/thread/detach). Either way before joining you should always check std::thread::joinable (https://en.cppreference.com/w/cpp/thread/thread/joinable).
The std::terminate is indeed most likely due to a running thread being destroyed and not being detached or joined before that. Note however that what happens to detached threads on application exit is implementation defined. If possible you should probably change the logic in those threads to allow graceful exit (std::jthread or std::atomic could help make stoppable threads):
EDIT:
Semi-complete C++17 "correct" code:
std::atomic stop{false};
std::vector<std::thread> threads;
threads.emplace_back(std::thread{[&] { while (!stop.load()) { /* */ }}});
threads.emplace_back(std::thread{[&] { while (!stop.load()) { /* */ }}});
//...
stop.store(true);
for (auto& thread : threads)
{
if (thread.joinable())
{
thread.join();
}
}
Semi-complete C++20 "correct" code:
std::vector<std::jthread> threads;
threads.emplace_back(std::jthread{[] (std::stop_token stopToken) { while (!stopToken.stop_requested()) { /* */ }}});
threads.emplace_back(std::jthread{[] (std::stop_token stopToken) { while (!stopToken.stop_requested()) { /* */ }}});
The C++20 std::jthread allows functions that take std::stop_token to receive a signal to stop. The destructor std::~jthread() first requests stop via the token and then joins so in the above setup basically no manual cleanup is necessary. Unfortunately only MSVC STL and libstdc++ currently support it while Clang's libc++ does not. But it is easy enough to implement yourself atop of std::thread if you'd fancy a bit of exercise.
What is the correct way of joining those threads?
Your way is fine, depending on what you're trying to do.
And is it actually necessary to join them?
Yes. And no.
See, the main issue with std::thread is that you need to clean them up or they'll "do bad things" (TM), but joining them is only one way of cleaning them up. The other way is to simply detach them from your actual threads, if you don't care to control them anymore (which seems to be the case?).
The things you need to ask yourself is if your setup makes sense, where you create a whole bunch of threads that don't end cleanly but instead are interrupted randomly by your entire process dying. What happens to the work they were supposed to do? If they write their output somewhere and it's interrupted half way through, are you, your employers and your customers okay with file corruption?

Multithreading a while loop in c++

I've started c++ (coming from a c# background), and in my program I need to run a while true loop, but since it is an imgui program the ui freezes up completely since I'm using Sleep() in the loop. I need to create a new thread but everything I've found online is just
std::thread nThread(Method);
nThread.join();
Now, the issue with this is it doesn't work at all since, I'm assuming, it's a while loop that's always running. I want to do the c++ equivalent of Thread thread = new Thread(method) and thread.Start(); in c#. If anyone can help me, I'd appreciate it.
t.join() waits for thread t to die. If you don't want the method that started the thread to wait for it, then don't join() it.
But note! The C++ library will get angry with you if you allow the thread object to be destroyed while the thread still is running. (The destructor will throw an exception.) If you want to tell the library, "Shut up! I know what I'm doing," you can detach the thread from the object. But usually it's a cleaner design if you can arrange for the object to live for as long as you need the thread to run.
Try a simple example and work from there.
void myFunc()
{
try
{
int x = 0;
while (x < 10)
{
sleep(1000);
std::cout<<"Thread is running"<<std::endl;
x++;
}
}
catch(Interrupted_Exception&) {
cout << "Caught Interrupted_Exception" << endl;
}
}
int main()
{
std::cout<<"Starting main"<<std::endl;
std::thread nThread(myFunc);
std::cout<<"Thread is running. Waiting for it to complete"<<std::endl;
nThread.interrupt();//in case the thread is sleeping
nThread.join();
std::cout<<"All done. Exiting"<<std::endl;
return 0;
}
Join means that the main thread has to wait for the worker thread. It's a way to ensure that the worker thread terminates before the caller. You only want to do that when you are terminating the program, in your case when the GUI is being close. Since at that time you want to tell the worker thread to stop right away, you call interrupt() on tell it to stop sleeping.
In the example, you can comment out the interrupt call so that the worker thread runs to completion.
There is no direct equivalent of that in the standard C++ library. When you use std::thread, the new thread starts immediately. You can simulate delayed start behaviour by making the thread stuck on a locked in advance mutex, then release mutex when you want the thread action to run actually. Aftwerwards you have to either join the thread or make it detached, otherwise std::thread destructor will throw an exception.
If you are on Windows, you can try to use Windows API directly (CreateThread() with flag CREATE_SUSPENDED, then ResumeThread() and finally posssibly TerminateThread() - if thread has sort of endless loop which never terminates in itself).
There is a way you can approach this and is using std::future and std::async with std::launch::async mode and throwing the function with the loop there.
std::future allows you to run a thread in the background and then after running give back the control to the parent thread so the program's flow can go as normal.
so you could have a boolean for the while and when std::future gives you back the control then you could modify this bool in the parent or main thread.

What happens to a thread, waiting on condition variable, that is getting joined?

I've got a class named TThreadpool, which holds member pool of type std::vector<std::thread>>, with the following destructor:
~TThreadpool() {
for (size_t i = 0; i < pool.size(); i++) {
assert(pool[i].joinable());
pool[i].join();
}
}
I'm confident that when destructor is called, all of the threads are waiting on a single condition variable (spurious wakeup controlled with always-false predicate), and joinable outputs true.
Reduced example of running thread would be:
void my_thread() {
std::unique_lock<std::mutex> lg(mutex);
while (true) {
my_cond_variable.wait(lg, [] {
return false;
});
# do some work and possibly break, but never comes farther then wait
# so this probably should not matter
}
}
To check what threads are running, I'm launching top -H. At the start of the program, there are pool.size() threads + 1 thread where TThreadpool itself lives. And to my surprise, joining these alive threads does not remove them from list of threads that top is giving. Is this expected behaviour?
(Originally, my program was a bit different - I made a simple ui application using qt, that used threadpool running in ui thread and other threads controlled by threadpool, and on closing the ui window joining of threads had been called, but QtCreator said my application still worked after I closed the window, requiring me to shut it down with a crash. That made me check state of my threads, and it turned out it had nothing to do with qt. Although I'm adding this in case I missed some obvious detail with qt).
A bit later, I tried not asserting joinable, but printing it, and found out the loop inside Threadpool destructor never moved further than first join - the behaviour I did not expect and cannot explain
join() doesn't do anything to the child thread -- all it does is block until the child thread has exited. It only has an effect on the calling thread (i.e. by blocking its progress). The child thread can keep running for as long as it wants (although typically you'd prefer it to exit quickly, so that the thread calling join() doesn't get blocked for a long time -- but that's up to you to implement)
And to my surprise, joining these alive threads does not remove them from list of threads that top is giving. Is this expected behaviour?
That suggests the thread(s) are still running. Calling join() on a thread doesn't have any impact on that running thread; simply the calling thread
waits for the called-on thread to exit.
found out the loop inside Threadpool destructor never moved further than first join
That means the first thread hasn't completed yet. So none of the other threads haven't been joined yet either (even if they have exited).
However, if the thread function is implemented correctly, the first thread (and all other threads in the pool) should eventually complete and
the join() calls should return (assuming the threads in the pool are supposed to exit - but this doesn't need to true in general.
Depending on application, you could simply make the threads run forever too).
So it appears there's some sort of deadlock or wait for some resource that's holding up one or more threads. So you need to run through a debugger.
Helgrind would be very useful.
You could also try to reduce the number of threads (say 2) and to see if the problem becomes reproducible/obvious and then you could increase the threads.

std::condition_variable without a lock

I'm trying to synchonise a set of threads. These threads sleep most of the time, waking up to do their scheduled job. I'm using std::thread for them.
Unfortunately, when I terminate the application threads prevent it from exiting. In C# I can make a thread to be background so that it will be termianted on app exit. It seems to me that equavalint feature is not availabe at C++.
So I decided to use a kind of event indicator, and make the threads to wake up when the app exits. Standard C++11 std::condition_variable requires a unique lock, so I cannot use it, as I need both threads to wake up at the same time (they do not share any resources).
Eventually, I decided to use WinApi's CreateEvent + SetEvent+WaitForSingleObject in order to solve the issue.
I there a way to achieve the same behavior using just c++11?
Again, what do I want:
a set of threads are working independently and usually are asleep
for a particular period (could be different for different threads;
all threds check a variable that is availabe for all of them whether
it is a time to stop working (I call this variable IsAliva).
Actually all threads are spinning in loop like this:
while (IsAlive) {
// Do work
std::this_thread::sleep_for(...);
}
threads must be able to work simultaneously, not blocking each other;
when the app is closed and event is risen and it makes the thread to
wake up right now, no matter the timeout;
waken up, it checks the
IsAlive and exits.
yes you can do this using standard c++ mechanisms of condition variables, a mutex and a flag of somekind
// Your class or global variables
std::mutex deathLock;
std::condition_variable deathCv;
bool deathTriggered = false;
// Kill Thread runs this code to kill all other threads:
{
std::lock_guard<std::mutex> lock(deathLock);
deathTriggered = true;
}
deathCv.notify_all();
// You Worker Threads run this code:
while(true)
{
... do work
// Now wait for 1000 milliseconds or until death is triggered:
std::unique_lock<std::mutex> lock(deathLock);
deathCv.wait_for(lock, std::chrono::milliseconds(1000), [](){return deathTriggered;});
// Check for death
if(deathTriggered)
{
break;
}
}
Note that this runs correctly in the face of death being triggered before entering the condition. You could also use the return value from wait_for but this way is easier to read imo. Also, whilst its not clear, multiple threads sleeping is fine as the wait_for code internally unlocks the unique_lock whilst sleeping and reacquires it to check the condition and also when it returns.
Finally, all the threads do wake up 'at the same time' as whilst they're serialised in checking the bool flag, this is only for a few instructions then they unlock the lock as they break out of the loop. It would be unnoticeable.
In c++11, you should be able to detach() a thread, so that it will be treated as a Daemon thread, which means the thread will be automatically stopped if the app terminates.

Is there a reliable way to force a thread to stop in C++? (especially detached ones)

I am recently working with threads in C++11. now I am thinking about how to force stop a thread. I couldn't find it on stackoverflow, and also tried these.
One variable each thread : not so reliable
return in the main thread : I have to force quit only one not all
and I have no more ideas. I have heard about WinAPI, but I want a portable solution. (that also means I wont use fork())
Can you please give me a solution of this? I really want to do it.
One of the biggest problems with force closing a thread in C++ is the RAII violation.
When a function (and subsequently, a thread), gracefully finishes, everything it held is gracefully cleaned up by the destructors of the objects the functions/threads created.
Memory gets freed,
OS resources (handles, file descriptors etc.) are closed and returned to the OS
Locks are getting unlocked so other threads can use the shared resources they protect.
other important tasks are preformed (such as updating counters, logging, etc.).
If you brutally kill a thread (aka by TerminateThread on Windows, for example), non of these actually happen, and the program is left in a very dangerous state.
A (not-so) common pattern that can be used is to register a "cancellation token" on which you can monitor and gracefully shut the thread if other thread asks so (a la TPL/PPL). something like
auto cancellationToken = std::make_shared<std::atomic_bool>();
cancellationToken->store(false);
class ThreadTerminator : public std::exception{/*...*/};
std::thread thread([cancellationToken]{
try{
//... do things
if (cancellationToken->load()){
//somone asked the thred to close
throw ThreadTerminator ();
}
//do other things...
if (cancellationToken->load()){
//somone asked the thred to close
throw ThreadTerminator ();
}
//...
}catch(ThreadTerminator){
return;
}
});
Usually, one doesn't even open a new thread for a small task, it's better to think of a multi threaded application as a collection of concurrent tasks and parallel algorithms. one opens a new thread for some long ongoing background task which is usually performed in some sort of a loop (such as, accepting incoming connections).
So, anyway, the cases for asking a small task to be cancelled are rare anyway.
tldr:
Is there a reliable way to force a thread to stop in C++?
No.
Here is my approach for most of my designs:
Think of 2 kinds of Threads:
1) primary - I call main.
2) subsequent - any thread launched by main or any subsequent thread
When I launch std::thread's in C++ (or posix threads in C++):
a) I provide all subsequent threads access to a boolean "done", initialized to false. This bool can be directly passed from main (or indirectly through other mechanisms).
b) All my threads have a regular 'heartbeat', typically with a posix semaphore or std::mutex, sometimes with just a timer, and sometimes simply during normal thread operation.
Note that a 'heartbeat' is not polling.
Also note that checking a boolean is really cheap.
Thus, whenever main wants to shut down, it merely sets done to true and 'join's with the subsequent threads.
On occasion main will also signal any semaphore (prior to join) that a subsequent thread might be waiting on.
And sometimes, a subsequent thread has to let its own subsequent thread know it is time to end.
Here is an example -
main launching a subsequent thread:
std::thread* thrd =
new std::thread(&MyClass_t::threadStart, this, id);
assert(nullptr != thrd);
Note that I pass the this pointer to this launch ... within this class instance is a boolean m_done.
Main Commanding shutdown:
In main thread, of course, all I do is
m_done = true;
In a subsequent thread (and in this design, all are using the same critical section):
void threadStart(uint id) {
std::cout << id << " " << std::flush; // thread announce
do {
doOnce(id); // the critical section is in this method
}while(!m_done); // exit when done
}
And finally, at an outer scope, main invokes the join.
Perhaps the take away is - when designing a threaded system, you should also design the system shut down, not just add it on.