Multithreading a while loop in c++ - 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.

Related

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.

Amateur can't understand std::thread usage

I hereby pardon for such a general title.
I am writing a physical simulation application which displays data in 3D using OpenGL, and one of the functions which is responsible for some heavy calculations is appearing to hold the performance down a bit. I would like them to be done "on the background" without freezing the application for a few seconds. However, std::thread doesn't seem to work in my case.
The function I am trying to thread has a lot of computations in it, it allocates some memory here and there, calls other functions and uses classes, if that matters. I've created a wrapper function, from which I try to start a thread:
void WrapperFunction(void)
{
std::thread t(DoSomethingSerious);
t.join();
}
However, it appears that it has zero effect, just like if I called DoSomethingSerious directly.
What could be the problem?
join() waits for the thread to finish, before proceeding. That's what joining a thread means.
You have two options.
1) Instantiating a std::thread, and proceed to do whatever else needs to be done, and only join the thread once everything is done.
2) detach() the thread. The detached thread will continue to execute independently, and cannot be joined any more. In this case, you will have to make other arrangements for waiting until the thread stops.
However, it appears that it has zero effect.
Sure, your code in the main thread is just suspended until everything in the asynchronous thread is finished.
If you have intermediate actions between starting the thread and doing the join(), you should notice the effect:
void WrapperFunction(void) {
std::thread t(DoSomethingSerious);
// Do something else in parallel
t.join();
}
That is because you directly call t.join(). The std::thread::join function waits for the thread to finish before returning. As you yourself notice, the effect is that there is no difference from just calling the function.
More useful would be to do something else between the thread creration and where you wait for the thread. Something like the following pseudo-code:
void WrapperFunction(void)
{
// Create thread
std::thread t(DoSomethingSerious);
// Lots
// of
// code
// doing
// other
// things
// Wait for thread to finish
t.join();
}

How to terminate or stop a detached thread in c++?

I am interested in terminating/stopping/killing a detached thread in c++. How can this be done?
void myThread()
{
int loop = 0;
while(true)
{
std::this_thread::sleep_for(std::chrono::seconds(5));
++loop;
}
}
void testThread()
{
std::thread globalThread(myThread);
globalThread.detach();
}
int main(void)
{
testThread();
for(unsigned int i=0; i < 1000; i++)
{
cout << "i = " << i << endl;
}
return 0;
}
The reason why I'd like to "stop"/"terminate" the globalThread() is because valgrind lists that this is a "possibly lost" type of memory leak (152 bytes). What is the best way to deal with this?
There are no provisions to stop another thread; whether it's detached, or joinable.
The only way to stop a thread, is for the thread to return from the initial thread function.
In this particular case, I would suggest the following changes:
Do not detach the thread. Instantiate it in main().
Add a bool value, and a std::mutex, the bool gets initialized to false
Each time through the thread's inner loop, lock the mutex using a std::unique_lock, take the bool's value, then unlock the mutex. After unlocking the mutex, if the bool was true, break out of the loop, and return.
In main(), before exiting: lock the mutex, set the bool flag to true, unlock the mutex, then join the thread
This is not perfect, since it will take up to five seconds for the second thread to check the bool flag, and return. But, this would be the first tep.
There is no way to cleanly shutdown a detached thread. Doing so would require waiting for the cleanup to complete, and you can only do that if the thread is joinable.
Consider, for example, if the thread holds a mutex that another thread needs to acquire in order to cleanly shut down. The only way to cleanly shut down that thread would be to induce it to release that mutex. That would require the thread's cooperation.
Consider if the thread has opened a file and holds a lock on that file. Aborting the thread will leave the file locked until the process completes.
Consider if the thread holds a mutex that protects some shared state and has put that shared state temporarily into a inconsistent state. If you terminate the thread, either the mutex will never be released or the mutex will be released with the protected data in an inconsistent state. This can cause crashes.
You need a thread's cooperation to cleanly shut it down.
You could drop below the C++ Standard and use OS-specific functions, such as sending your own process a signal while setting the signal mask so it's delivered only to the detached thread - a handler can set a flag that's polled from your thread. If your main routine waits longer than the poll period plus a bit you can guess it should have terminated ;-P. The same general idea can be used with any other signalling mechanism, such as an atomic terminate-asap flag variable.
Alternatively, and only as a last resort, there's pthread_cancel and similar. Note that async cancellation like this is a famously dangerous thing to do in general - you should be careful that the thread you terminate can't be in any code with locked/taken resources or you may have deadlocks, leaks, and/or undefined behaviour. For example, your code calls std::this_thread::sleep_for(std::chrono::seconds(5)); - what if that asks the OS for a callback when the interval expires, but the function to continue to afterwards uses the terminated thread's stack? An example where it can be safe is if the thread's doing some simple number crunching in a loop within your app.
Otherwise Sam's answer documents an alternative if you avoid detaching the thread in the first place....
In noticing that the straight forward answer of "NO" is less than helpful:
Generally you will see the answer being akin to "use your own inter thread communication"
Whether that is an atomic bool being shared between the main thread and the child thread or whether that is signalling a thread with another thread via OS methods.
It may be helpful to shift the focus to the specifics of WHEN you would like a detached thread to die, rather than 'who does the killing'.
https://en.cppreference.com/w/cpp/thread/notify_all_at_thread_exit
Looking at code examples like the above helped me with what I was dealing with (main thread dying obscurely and children segfaulting) and I hope it helps you.
I think the best way is to create signal handler
#include <iostream>
#include <csignal>
using namespace std;
void signalHandler( int signum ) {
cout << "Interrupt signal (" << signum << ") received.\n";
// cleanup and close up stuff here
// terminate program
exit(signum);
}
int main () {
// register signal SIGINT and signal handler
signal(SIGINT, signalHandler);
while(1) {
cout << "Going to sleep...." << endl;
sleep(1);
}
return 0;
}
https://www.tutorialspoint.com/cplusplus/cpp_signal_handling.htm
this is the site where I got the code. You can also use raise function to create signal in the code. Checkout the link.
You can terminate the detached thread by setting its condition to break the loop though the pointer.
You can also wait for that thread until it finishes execution using semaphore.

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

I heard that "a modern operating system will clean up all threads created by the process on closing it" but when I return main(), I'm getting these errors:
1) This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
2) terminate called without an active exception
My implementation looks like this (I'm writing now for example sorry for bad implementation):
void process(int id)
{
while(true) { std::this_thread::sleep_for(std::chrono::milliseconds(1); } }
}
int main()
{
std::thread thr1(process, 0);
std::thread thr2(process, 1);
//thr1.detach();
//thr2.detach();
return 0;
}
If I uncomment detach();s, there is no problem but my processing threads will be socket readers/writers and they will run infinitely (until main returns). So how to deal with it? What's wrong?
EDIT: Namely, I can't detach() every thread one-by-one because they will not be terminated normally (until the end). Oh and again, if I close my program from the DDOS window's X button, (my simple solution not works in this case) my detach(); functions being passed because program force-terminated and here is the error again :)
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.

Waiting for a std::thread to finish

I am trying to clean up gracefully on program termination, so I'm calling join() on a std::thread to wait for it to finish. This simply seems to block the main thread forever, but I don't understand why, because the worker thread is an (almost) empty loop like this:
void GameLoop::Run()
{
while (run)
{
// Do stuff...
}
std::cout << "Ending thread...\n";
}
I'm setting run to false before joining, of course. Now, I'm suspecting it's got something to do with it being a member function and being called upon object destruction. I'm creating the thread like this: runThread.reset(new thread(&GameLoop::Run, this));, where runThread is unique_ptr<std::thread> and a member of GameLoop. The join() call comes in the destructor of the GameLoop object.
Maybe the loop thread cannot finish if its object is in the process of being destroyed? According to the debugger the loop thread lingers on in the dark depths of msvcr120d.dll. If so, how would you handle it?
Beware: new to std::thread here!
Update: This is my call to join in the destructor:
run = false;
if (runThread->joinable())
{
runThread->join();
}
Update 2: If I remove the join() I get an exception raised by ~thread()!
Of course, when you join a thread that doesn't cause the thread to terminate. It simply blocks until that thread dies of natural (or unnatural) causes.
In order to clean up a multithreaded application gracefully, you need to somehow tell the worker thread that it is time to die, and then wait for the death to happen. The "wait for death to happen" part is what join is for.
Ahh, apparently there's a bug in the runtime library. Threads are not ended successfully in destructors of static objects according to this question. My GameLoop is a non-static object contained in a static GameSystem. I'll check whether this is true and update.
Yep, confirmed. Just my luck to hit a bug on first use!