when to detach or join a boost thread? - c++

I have a method which is fired once every 30 seconds aprox. that I need to have in a thread.
I have a method that I can call from outside the class. Something like callThreadedMethod() which creates the thread which itself calls the final threadedMethod.
These are methods of MyClass
void callThreadedMethod(){
mThread = boost::shared_ptr<boost::thread>(new boost::thread(&MyClass::threadedMethod, this));
}
void threadedMethod(){
//more code NOT inside a while loop
}
So do I have to detach mThread every time the method is called?
Is it enough to call join() in the MyClass destructor?
Does the thread destroys itself when threadedMethod finishes?

It depends what you want to achieve. If you don't care when or if the calls to threadedMethod terminate, or whether or not they throw, then you can just detach the thread as soon as you've created it; each thread will be destroyed when the method completes. And you shouldn't store the thread in a member variable.
If you do care then you need to call join on each thread you create (so once per thread, not once in the destructor). I suspect you don't.
Do you really need to create a new thread for each call? Thread creation can be expensive, so an alternative would be to use a thread pool and submit each threadedMethod invocation to that. The pool could then have the lifetime of the MyClass instance. But perhaps that's overkill for something that is only happening once every 30s.

Related

C++11: How can I join a std::thread as soon as its execution function exits?

I have the following class that has a std::thread as one of its member fields:
class MyClass {
private:
std::thread auxThread;
void run();
public:
~MyClass();
void start();
}
MyClass:~MyClass() {
if (auxThread.joinable())
auxThread.join();
}
void MyClass::run() {
//do stuff
}
void MyClass::start() {
auxThread = std::thread (&MyClass::run, this); //Move assignment
}
I can start the auxThread on-demand thanks to initializing it with an empty constructor and later move-assigning it to a std::thread object associated with an actual thread of execution (via the start() function), but to minimize system resource usage I'd like to join() auxThread with the main thread immediately after run() has exited i.e. when auxThread's work is done instead of in the MyClass destructor. It looks like condition_variable could be used to wake a sleeping main thread and accomplish this, but I don't want to block the main thread except (hopefully) briefly with join().
Two questions:
Is having a thread whose execution function has exited a drain on resources if it is never joined with the main thread, or is the thread and all associated resources released when the execution function exits (such that join() would presumably be unnecessary and return immediately)?
Is it possible to call join() on auxThread from the main thread in response to run() exiting without blocking the main thread?
Is having a thread whose execution function has exited a drain on resources if it is never joined with the main thread
Maybe. It depends on your implementation, but typically not.
is the thread and all associated resources released when the execution function exits
Probably, and if not, then as soon as possible by the OS. This is also implementation defined.
Is it possible to call join() on auxThread from the main thread in response to run() exiting without blocking the main thread?
Yes, but it wouldn't make any sense. The only thing that join does is block until the function being executed is done. Calling join again after run finished executing is unnecessary and basically a no-op.
Also, the "resources" from the thread are minimal. I wouldn't expect that a lot of memory would be allocated just for a single thread like yours. RAM is pretty cheap nowadays, so you shouldn't worry about that, as you are not executing 5M threads in parallel, which would make no sense on a conventional computer anyways.

Starting thread causing abort()

I'm trying to create a thread with the regular c++11 threads.
I have an object called NetworkManager that creates a thread of one of its methods in its constructor like this:
void NetworkManager()
{
// Raknet setup here...
std::thread networkUpdate(&NetworkManager::update, this);
// Set timers
playerDataTimer.start();
playerDataTimer.pause();
Logger::log("NetworkManager constructor ended");
}
The update method handles the messages coming on from other clients via the RakNet library like here: Link
I did the same thing as in the example where it's encapsulated in a while loop that keeps going forever.
When I try to create this thread in the constructor however I get an abort() message (the application crashes) and I can't figure out why this is. All objects that are used in the thread are setup before the loop starts so I don't think that's the issue.
The std::thread object you're creating gets destroyed at the end of your constructor since it is a local variable. If the destructor of a std::thread is called while the thread is joinable (like it is in your example), std::terminate is called.
You must keep that thread object as a member of your class, or store it somewhere else, or detach the thread. (Or join with it in your constructor, but that doesn't sound like it would do what you want.)
Your app terminates because the std::thread is destructed without being .detached or .joined.
~thread();
Destroys the thread object.
If *this has an associated thread (joinable() == true), std::terminate() is called.

How to safely delete a thread pointer in a destructor?

Say, I have a C++ class including a thread pointer as a member variable. The thread keeps running until the program exits. If I delete the pointer in the destructor, it seems that the thread has not yet finished at that moment? What is the best practice to manage this or any tricks?
Sample code:
class Car {
public:
Car();
~Car();
private:
boost::thread *m_runningThreadPtr;
};
Car::Car() {
m_runningThreadPtr = new boost::thread();
}
Car::~Car() {
delete m_runningThreadPtr; // The thread should be still running now.
// Problematic if it was deleted here?
}
By default the destructor will call terminate() to kill the thread if it's still running, whether this is safe or not depends on what the thread is doing at the time. You can call join() before deleting it if you want to wait for the thread to finish, and use some sort of synchronization system (even just a global flag) that tells the thread to quit.
It depends on what kind of behavior you're looking for.
If you want to delete the object, and have it stop its owned thread and then delete its thread object, then you should have a stop flag which your thread checks from time to time. In the destructor, you'd set the stop flag, and then call join() on your thread. Once it returns, you can safely delete the pointer.
If, on the other hand, you want to delete the object and have the thread go on its own until it finishes, then you need a more clever mechanism, like at the end of your thread function, posting to the main thread of your application a callback that calls join() on your thread and then deletes it. For that, of course, you'll need to have in your thread function a pointer to your thread object.
EDIT
In the case of boost::thread, it simply detaches in its destructor, so for the second option you can safely delete it when you're done.
It's important to note, however, that this won't work with std::thread's destructor, which will terminate your program in such a case. But then you can also manually call detach() and then delete. So you really have to look at the API you're using.
Don't delete it. Have the thread delete itself when done.
Your program is done when there's no more code to run. Are your threads still running code? Then why do you think your program is done?
So, it's reasonable to assume your threads are i fact done. That means you can call .join() on the thread, after which it is OK to call delete.

Boost thread object lifetime and thread lifetime

I would like to have boost thread object being deleted together with exiting from thread entry function. Is it something wrong if I start the thread function and pass a shared pointer to object, which owns thread object instance and then, when thread function exits, it destroys the this object together with thread object at the same time?
EDIT:
Maybe I will describe why I want to do that. I have to use low level dbus API. What I want to do is to create the adapter class, which will start its own thread and wait for incoming messages until the DISCONNECT message arrives. If it arrives I want to close the thread and kill the Adapter itself. The adapter is an Active Object, which runs the method sent to its scheduler. These methods put themselves on the scheduler queue once again after reading message from dbus. But if it is DISCONNECT message, they should not sent the method but just exit scheduler thread, destroying the Adapter object. hmmm looks like it is too complicated...
From the Boost.Thread documentation you can see that a thread object that is joinable should not be deleted, otherwise std::terminate will be called.
So you should assure that if the thread is joinable, either join() or detach() should be called in the destructor of the object owning the thread. Note: if the thread itself is destroying the object, join() is not an option. The thread would attempt to join itself, resulting in a deadlock.
However, if you keep these restrictions in mind, you can destroy a thread from within its own thread of execution.
You can do this, but you probably should not.
The main purpose of the boost::thread object is that you can monitor the associated thread. Having a thread monitor itself does not make much sense in most scenarios.
As was suggested by the other answers, you could just detach the thread and throw the boost::thread object away. Doing this is usually considered bad style, unless the monitoring responsibility has been transferred to another object first. For example, many simple worker threads set a future upon completion. The future already provides all the monitoring we need, so we can detach the thread.
You should never detach a thread completely such that you lose all means of monitoring it. You must at least be able to guarantee a clean shutdown, which becomes impossible for all but the most trivial threads if you detach them completely.
I am not sure if that addresses your use case but it sounds to me like you don't have to do this.
The lifetime of the boost::thread object does not necessarily coincide with the thread itself. Meaning that if you don't care you can just as well start the thread, call detach() on it and have the object run out of scope. Then it is deleted but the thread will still run until it's function is finished. The only thing is, you won't be able to join it. So if your program finishes while the thread still runs it will crash.
In case you do care about this stuff, the question might be wrong because in this case you would store the objects and call join() on them before deleting.

What’s the best way to delete boost::thread object right after its work is complete?

I create boost::thread object with a new operator and continue without waiting this thread to finish its work:
void do_work()
{
// perform some i/o work
}
boost::thread *thread = new boost::thread(&do_work);
I guess, it’s necessary to delete thread when the work is done. What’s the best way to this without explicitly waiting for thread termination?
The boost::thread object's lifetime and the native thread's lifetime are unrelated. The boost::thread object can go out of scope at any time.
From the boost::thread class documentation
Just as the lifetime of a file may be different from the lifetime of an iostream object which represents the file, the lifetime of a thread of execution may be different from the thread object which represents the thread of execution. In particular, after a call to join(), the thread of execution will no longer exist even though the thread object continues to exist until the end of its normal lifetime. The converse is also possible; if a thread object is destroyed without join() having first been called, the thread of execution continues until its initial function completes.
Edit: If you just need to start a thread and never invoke join, you can use the thread's constructor as a function:
// Launch thread.
boost::thread(&do_work);
However, I don't suggest you do that, even if you think you're sure the thread will complete before main() does.
You can use
boost::thread t(&do_work);
t.detach();
Once the thread is detached it is no longer owned by the boost::thread object; the object can be destroyed and the thread will continue to run. The boost::thread destructor also calls detach() if the object owns a running thread, so letting t get destroyed will have the same result.
I suggest you use boost::shared_ptr, so you won't take care when to delete thread object.
boost::shared_ptr<boost::thread> thread(new boost::thread(&do_work));
You should take a look at thread interruption.
This article is good also.
http://www.boost.org/doc/libs/1_38_0/doc/html/thread/thread_management.html