To use or not to use join() method with infinite loops - c++

Suppose an object X is supposed to run forever. X is running threads with infinite loops inside, so the program will never exit.
My question is this: is it a good practice to put use the join() method at all, for example, in the deconstructor, or would it make more sense to do something like
int main() {
X myX;
while(1) {
}
return 0;
}
Are there any differences between the two approaches?

Sometimes it is required, often it is not. If you can design your app so that it does not, so much the better.

You would want to call join() if some part of your program needed to wait to run until a thread exited. It also makes the thread object destroyable so you don't create a memory leak. Threads that haven't been joined are like zombie processes and waste resources.

Related

Is there a way to join a thread in another function? (I.E. Outside of it's own scope)

Let's say I am creating multiple threads, based on the amount of arguments I gave to the program when I ran it. The code for it would something like this:
ProgThread aProgThreads[nArgc-1];
for(int p=0;p<nArgc-1;p++){
aProgThreads[p].init();
}
The code above would create an object for every argument. After that, it will call the init() function for every object. In this function the thread will be made like this:
void ProgThread::init(){
std::thread oMainThread(&ProgThread::loop, *this); //Creates a thread that executes the loop function
}
Now, because I'm dealing with multiple threads I want to execute at the same time I can't join them within the init() function. This means I have to join them after they have all been created. The way this code is currently written, this isn't possible because oMainThread won't exist outside of the init() function. Is there a way I can make it so I can have a seperate loop that joins all the threads? It would look something like this:
for(int p=0;p<nArgc-1;p++){
aProgThreads[p].joinThread();
}
Coupled with
void ProgThread::joinThread(){
oMainThread.join();
}
Thanks in advance!
The chief problem in your example is std::thread oMainThread in onInit. This creates a thread, yes, but it also tries to destroy the thread when you return from onInit. And that will indeed fail, because oMainThread has not been joined.
Instead, the join needs to be in the destructor of ProgThread, which means oMainThread needs to be a member. And of course, like all members, it should be initialized in the constructor of ProgThread.
The only reason why you'd want a loop is when your threads need to be told when to stop before joining. In that case, it can be wise to tell all threads to stop, and only then start joining them. It would take more time to tell one thread to stop, then join that thread, then tell the next, etcetera.

How to use thread by using c++ in my case?

I have a function to calculate the value in real time
void task() {
while(true) {
...//calculate value(value will change every loop)
}
}
In the main thread, my code is as follow, i want to use the real time value which i got from task thread,
int main() {
...
while(true) {
int v = value;//value is calculated from task thread in real time
....
}
}
The main Thread will cost about 0.5s one loop, so i want to get the lastest value to update the v in next loop,How can i do this?
It's my first time to use Thread in c++,i don't know how to write the code.Can someone help me.Thanks in advance!!
Have a look at std::thread for basic threading in general. In case of an int depending on the platform, it might simply work. If you want to be sure, use an std::atomic<int>
std::atomic<int> global_value;
void task() {
while(true) {
...//calculate value(value will change every loop)
global_value.store(value);
}
}
int main() {
...
while(true) {
int v = global_value.load();
....
}
}
std::atomic<int> will make sure, that all read and write accesses are atomic.
Make the variable outside main, and above functions.
One thing you could additionally do, is make your function recursive. Then set it up in a <thread>, which if you haven't already included, then you're not close to done. A thread is a separate routine running the whole time your other tasks are running. A recursive function is one that calls itself unless one base case is reached. Then it returns. So we need to change your thread's variable, which you can do easily just by following what I said above. Thread instructions at cplusplus.com will help you more. So do try and research it. It's out there. And if you want top level help, there's books as well. You need to have the reading skills to look at code the right way. And the only way you'll learn independence is to stalk the information down and learn it. It's old school, but it'll always work.
std::thread first (task,arg);
That instances your thread, and you've called it first. So all methods are going to be referenced through first. like first.join() which will meet you back up with the thread, after you've first.detach() from it. In the case you do, you have to .join() again to destroy it. Much like a pointer. It has become independent of the program at that point, and is running in the background.
If you want to destroy it
first.~thread();

Use of fork for executing multiple commands

I have a list of class pointers. I have a function that calls a method from these pointers. Each pointer in the list is a derived class from a main class. What i am currently doing is iterate through the list and call the method of 1st pointer in the list, wait for it to finish, then go to the 2nd class object pointer and call the method and so on.
Now i have like 20 derived classes and it is taking forever to complete through the list. So i wanted to use fork to execute maybe 4-5 class methods at once so that the whole process is that much fast..
list<Myclass *> check;
myfunc(list<Myclass *> check)
{
for(list<Myclass*>::iterator a= check.begin();a!=check.end();a++)
(*a)->run();
}
this is kinda a skeleton of what i have...
What i want is like each time it will fork and create a child process to execute the command and moveon to the next one...
Yes, you can use fork() to do some work in a child thread. However, once the child process is done doing it's work, it returns and you are not sharing data between them. I am not clear on your implementation but if the intent is to spawn off some processes to do some extra work, then that seems OK, but you probably want a thread, not fork.
You are more likely to want to start a thread than fork a process. It is easier when there are pointers involved, since pointers can be shared inside a process but not outside.
Also, forking a process has some performance overhead.
So i wanted to use fork to execute maybe 4-5 class methods at once so that the whole process is that much fast..
As many others have already mentioned, you probably want to use threads rather than fork here. There is a lot more overhead with fork than there is with spawning a new thread.
What others have not said is that spawning a thread or a process does not guarantee a speedup. For example, you might will get a slowdown rather than a speedup if you spawn many more CPU-bound threads at once than the number of available CPUs. What happens is that each of those threads compete with the others for their turn on the limited number of CPUs. A thread will run a little bit of time and then be swapped out for another.
It's a good idea to make the number of active threads less than the number of CPUs available. Even if you do that, you can still run into trouble when some other CPU-bound application happens to be running at the same time.
You're not passing any memory back with fork though. You probably want a thread. Here's how to do it though:
int i = 0;
int n = 4; //or 5;
list<Myclass> check; // You can't use pointers here though, as the memory is not shared.
myfunc(list<Myclass> check)
{
for(list<Myclass>::iterator a= check.begin();a!=check.end();a++) {
if(i >= n) {
wait();
} else {
if(fork() == 0) {
a->run();
exit(0);
} else {
i++;
}
}
}
// Prevent a voodoo priest from making zombies of these processes.
while(i-->0) wait();
}

kill boost thread after n seconds

I am looking for the best way to solve the following (c++) problem. I have a function given by some framework, which returns an object. Sometimes it takes just miliseconds, but on some occasions it takes minutes. So i want to stop the execution if it takes longer than let's say 2 seconds.
I was thinking about doing it with boost threads. Important sidenote, if the function returns faster than the 2 seconds the program should not wait.
So i was thinking about 2 threads:
1.thread: execute function a
2.thread: run timer
if(thread 2 exited bevore thread 1) kill thread 1
else do nothing
I am struggeling a bit the practical implementation. Especially,
how do i return an object from a child boost thread to the main thread?
how do i kill a thread in boost?
is my idea even a good one, is there a better way to solve the problem in c++ (with or without boost)?
As for waiting, just use thread::timed_join() inside your main thread, this will return false, if the thread didn't complete within the given time.
Killing the thread is not feasible if your third-party library is not aware of boost:threads. Also, you almost certainly don't want to 'kill' the thread without giving the function the possibility to clean up.
I'd suggest that you wait for, say, 2 seconds and then continue with some kind of error message, letting the framework function finish its work and just ignoring the result if it came too late.
As for returning a value, I'd suggest something like
struct myfunction {
MyObj returnValue;
void operator() () {
// ...
returnValue = theComputedReturnValue;
}
};
// ...
myfunction f;
boost::thread t = boost::thread(boost::ref(f));
t.join(); // or t.timed_join()...
use(f.returnValue);
// ...
I have done something similar by the past and that works (even though not ideal).
To get the return value just "share" a variable (that could be just a pointer (initially nil) to the returned value, or a full object with a state etc ...) and make your thread read/udate it. Don't forget to mutex it needed. That should be quite straight forward.
Expanding what James has said above, "kill a thread" is such a harsh term! :) But interruption is not so easy either, typically with boost threads, there needs to be an interruption point, where the running thread can be interrupted. There is a set of these interruptible functions (unfortunately they are boost specific), such as wait/sleep etc. One option you have is in the first thread, liberally scatter interruption_points(). Such that when you call interrupt() once thread 2 dies, at the next interruption_point() thread 1 will throw an exception.
Threads are in the same process space, thus you can have shared state between multiple threads as long as there is synchronized access to that shared state.
EDIT: just noticed that the OP has already looked into this... will leave the answer up anyway I guess...

C++ Thread question - setting a value to indicate the thread has finished

Is the following safe?
I am new to threading and I want to delegate a time consuming process to a separate thread in my C++ program.
Using the boost libraries I have written code something like this:
thrd = new boost::thread(boost::bind(&myclass::mymethod, this, &finished_flag);
Where finished_flag is a boolean member of my class. When the thread is finished it sets the value and the main loop of my program checks for a change in that value.
I assume that this is okay because I only ever start one thread, and that thread is the only thing that changes the value (except for when it is initialised before I start the thread)
So is this okay, or am I missing something, and need to use locks and mutexes, etc
You never mentioned the type of finished_flag...
If it's a straight bool, then it might work, but it's certainly bad practice, for several reasons. First, some compilers will cache the reads of the finished_flag variable, since the compiler doesn't always pick up the fact that it's being written to by another thread. You can get around this by declaring the bool volatile, but that's taking us in the wrong direction. Even if reads and writes are happening as you'd expect, there's nothing to stop the OS scheduler from interleaving the two threads half way through a read / write. That might not be such a problem here where you have one read and one write op in separate threads, but it's a good idea to start as you mean to carry on.
If, on the other hand it's a thread-safe type, like a CEvent in MFC (or equivilent in boost) then you should be fine. This is the best approach: use thread-safe synchronization objects for inter-thread communication, even for simple flags.
Instead of using a member variable to signal that the thread is done, why not use a condition? You are already are using the boost libraries, and condition is part of the thread library.
Check it out. It allows the worker thread to 'signal' that is has finished, and the main thread can check during execution if the condition has been signaled and then do whatever it needs to do with the completed work. There are examples in the link.
As a general case I would neve make the assumption that a resource will only be modified by the thread. You might know what it is for, however someone else might not - causing no ends of grief as the main thread thinks that the work is done and tries to access data that is not correct! It might even delete it while the worker thread is still using it, and causing the app to crash. Using a condition will help this.
Looking at the thread documentation, you could also call thread.timed_join in the main thread. timed_join will wait for a specified amount for the thread to 'join' (join means that the thread has finsihed)
I don't mean to be presumptive, but it seems like the purpose of your finished_flag variable is to pause the main thread (at some point) until the thread thrd has completed.
The easiest way to do this is to use boost::thread::join
// launch the thread...
thrd = new boost::thread(boost::bind(&myclass::mymethod, this, &finished_flag);
// ... do other things maybe ...
// wait for the thread to complete
thrd.join();
If you really want to get into the details of communication between threads via shared memory, even declaring a variable volatile won't be enough, even if the compiler does use appropriate access semantics to ensure that it won't get a stale version of data after checking the flag. The CPU can issue reads and writes out of order as long (x86 usually doesn't, but PPC definitely does) and there is nothing in C++9x that allows the compiler to generate code to order memory accesses appropriately.
Herb Sutter's Effective Concurrency series has an extremely in depth look at how the C++ world intersects the multicore/multiprocessor world.
Having the thread set a flag (or signal an event) before it exits is a race condition. The thread has not necessarily returned to the OS yet, and may still be executing.
For example, consider a program that loads a dynamic library (pseudocode):
lib = loadLibrary("someLibrary");
fun = getFunction("someFunction");
fun();
unloadLibrary(lib);
And let's suppose that this library uses your thread:
void someFunction() {
volatile bool finished_flag = false;
thrd = new boost::thread(boost::bind(&myclass::mymethod, this, &finished_flag);
while(!finished_flag) { // ignore the polling loop, it's besides the point
sleep();
}
delete thrd;
}
void myclass::mymethod() {
// do stuff
finished_flag = true;
}
When myclass::mymethod() sets finished_flag to true, myclass::mymethod() hasn't returned yet. At the very least, it still has to execute a "return" instruction of some sort (if not much more: destructors, exception handler management, etc.). If the thread executing myclass::mymethod() gets pre-empted before that point, someFunction() will return to the calling program, and the calling program will unload the library. When the thread executing myclass::mymethod() gets scheduled to run again, the address containing the "return" instruction is no longer valid, and the program crashes.
The solution would be for someFunction() to call thrd->join() before returning. This would ensure that the thread has returned to the OS and is no longer executing.