In my program I have a static object that creates a boost::thread. The thread is supposed to run until program termination, but it shouldn't be terminated in random state, so I implemented controled thread termination in this static object's destructor. The problem is that when main() terminates my thread is terminated before the destructor is called.
Now the question: is it possible to prevent the thread to be destroyed? Or at least delay it, so that it happens after the destructor is called?
Move the termination from the destructor to a function and simply call it before main ends.
Related
I have an object that uses pthreads. Its constructor creates several threads.
The class's destructor calls pthread_join on all these threads.
What would happen during a delete, if it didn't? I.e., what happens to a non-terminated thread, if the delete operator suddenly tries to deallocate the object?
Thanks in advance for all replies. :)
With the join, your destructor will block until all of the joined threads have exited.
pthread_join
The pthread_join() function waits for the thread specified by thread
to terminate. If that thread has already terminated, then
pthread_join() returns immediately. The thread specified by thread
must be joinable.
If you don't join with the threads, they will continue to run. This can have various consequences depending on if you invoke undefined behavior (eg, try to reference the deleted object after the destructor exits from one of the still running threads).
Deleting the pthread_t objects could have consequences depending on your system (I don't know every implementation of pthreads), but in general they're only references to the underlying system object representing the thread. So you will lose your reference to that thread, and potentially be unable to join with it later, but the thread would continue to run.
So I have a strange situation here. I have the following code:
int main()
{
std::shared_ptr<MyClassA> classA = std::shared_ptr<MyClassA>(new MyClassA);
std::shared_ptr<MyClassB> classB = std::shared_ptr<MyClassB>(new MyClassB(classA));
boost::thread_group threadGroup;
// This thread is essentially an infinite loop waiting for data on a socket
threadGroup.create_thread( boost::bind(&MyClassB::method1, classB) );
...do stuff
return 0;
}
MyClassB opens several resources, that are not deallocated when the program exits. However, if I remove the call to create_thread, the resources are deallocated. I put a printout in the destructor of MyClassB, and verified that it's not being called if that thread is created.
Anybody have any insight into what's going on here?
According to documentation boost::thread_group destructor destroys all onwed thread. boost::thread destructor in order:
if defined BOOST_THREAD_DONT_PROVIDE_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE: If *this has an associated thread of execution, calls detach(), DEPRECATED
BOOST_THREAD_PROVIDES_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE: If the thread is joinable calls to std::terminate. Destroys *this.
So you need to join threads explicitly. You can do that by calling boost::thread_group::join_all() at the end of your program.
Since you are passing shared pointer to class B to your thread, your thread now shares the instance. Until this threads exits NATURALLY, this resource will not be freed.
// This thread is essentially an infinite loop waiting for data on a socket
This comment is very telling. Your thread may run forever, well past the end of the program. If that's the case, you need to detach the thread before you exit main, and you should expect not to see the destructor called. The thread is still alive and shares ownership of that object.
...do stuff
If that ...do stuff doesn't involve either detaching or joining that thread, you are invoking undefined behavior in Boost. That undefined behavior becomes very well defined if you switch from using boost::thread to using std::thread.
That well-defined behavior is something that no sane programmer wants to invoke: Destructing a joinable thread results in a call to std::terminate(). The behavior of std::terminate is implementation-dependent, but typically it means "stop right now". Destructors aren't called, exit handlers aren't called.
You need to either join or detach that thread.
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.
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.
I have some code which I did not originally create that uses _beginthreadex and _endthreadex. For some reason, when it calls _endthreadex(0), the call just hangs and never returns. Any ideas as to what would normally cause this call to hang?
My answer is too far late, but still someone will use it.
In my case _endthreadex hanged when I unload dll and deleted some global objects. One of global objects had another thread inside and that thread also performed thread exit. This caused deadlock since DLLMain already locked crt memory map. Read DLLMain help and find that you are not allowed do any other action on another threads or processes during DLLMain call.
_endthreadex ends the thread, so it can't return. That's the whole point of calling it.
EDIT: It's a bit unusual to call _endthreadex, normally you just let the thread start procedure return and the runtime calls _endthreadex for you. You may need to explain a bit more, what you are trying to do before we can help.
Are you mistakenly calling _endthreadex() to attempt to end a thread from the main thread?
The function _endthreadex() is meant to be called inside the thread that you want to terminate to report a return value, and for the proper "recovery of resources allocated for the thread." You shouldn't need to call it in a destructor from the main thread. You could, in a destructor, signal to the thread via an event (see SetEvent, called from the main thread) that the thread should exit as soon as possible, and then the thread that is exiting as its last statement would call _endthreadex().
Calling _endthreadex() in your main thread would cause the process to hang, because you've terminated your main thread, but you would still have the original thread you wanted to terminate still running.
Ok....well, endthreadex gets called in the deconstructor of my class via "delete classinstance"...and that deconstructor call never returns...so the whole thing hangs