How do I know if a boost thread is done? - c++

I am using boost::thread to process messages in a queue.
When a first message comes I start a message processing thread.
When a second message comes I check if the message processing thread is done.
if it is done I start a new one
if it is not done I don nothing.
How do I know if the thread is done ? I tried with joinable() but it is not working, as when the thread is done, it is still joinable.
I also tried to interrupt the process at once, and add an interruption point at the end of my thread, but it did not work.
Thanks
EDIT :
I would like to have my thread sleep for an undetermined time, and wake up when a signal is triggered.
The mean to do it is boost::condition_variable

As far as I know you should use the join() method to wait the end of a thread execution. You can use it with a timeout with timed_join().
You can interrupt threads with interrupt(). In this case, inside the thread an exception will occur if the execution reaches an interruption point ( a boost::this_thread::sleep() or boost::this_thread::interruption_point() ). You catch the exception inside the thread and you can then close it.

Spawning a new thread for each incoming message is very inefficient. You should check out the Thread pool pattern.
EDIT:
Sorry, jules, I misread your question. I recommend you take a look at the producer-consumer pattern. Check out this article on how to roll your own blocking queue using boost condition variables. Intel's Thread Building Blocks also has a blocking queue implementation.
Check out this SO question about existing lock-free queue implementations.
Hope this helps.

Have you tried checking get_id() with boost::this_thread::get_id(). If they match the thread does not exist. But that will only happen if you have exited the thread.

Related

Ordered notification of threads waiting on a condition (C++, boost)

Does anyone know of a condition variable class that allows notification of threads waiting for a condition to be notified in the order in which they started waiting?
I'm currently using the boost class condition_variable, but calling condition_variable::notify_one() wakes up a random thread, not the thread that first called condition_variable::wait(). I also tried adding thread ids to a queue before calling condition_variable::wait(), so that I can call condition_variable::notify_all() upon which all waiting threads wake up, check the queue and either wait again or proceed (only one thread, namely the thread first in queue). The problem is that calling notify_all() twice does not guarantee that all threads are waking up twice, thereby losing notifications. Any suggestions?
It is strange that you require threads to be woken in particular order and sounds suspicious about your design. Anyway idea is that you can have queue of condition variables (one per thread) and you would call notify_one() for one from top of the queue. In waiting thread you need to do additional logic to check that it was not sporadically interrupted from wait. Again sounds strange why you need thread to wake up in particular order and you may want to rethink your design.

Do you need to join a cancelled thread? (pthreads)

I'm a little confused about clean-up order when you're using PThreads with regard to cancellation. Normally, if your thread is detached, it automatically cleans up when it terminates. If it's not detached, you need to join it to reclaim the system resources.
The textbook I'm reading states the following which strangely sounds like joining is optional with regard to cancellation:
"If you need to know when the thread has actually terminated, you must
join with it by calling pthread_join after cancelling it."
So, do I need to join a cancelled thread to free its resources - and if not, then why?
TLPI says this:
Upon receiving a cancellation request, a thread whose cancelability is
enabled and deferred terminates when it next reaches a cancellation
point. If the thread was not detached, then some other thread in the
process must join with it, in order to prevent it from becoming a
zombie thread.
Also, since canceling a thread isn't usually done immediately (read more about "cancellation points") without joining you can't be sure the thread was actually canceled.
From man pthread_join:
After a canceled thread has terminated, a join with that thread using
pthread_join(3) obtains PTHREAD_CANCELED as the thread's exit status.
(Joining with a thread is the only way to know that cancellation has
completed.)
It seems that joining is not necessary for execution it is necessary if you want know what you did actually succeed.
From Doccumentation of pthread_cancel():
After a canceled thread has terminated, a join with that thread using pthread_join(3) obtains PTHREAD_CANCELED as the thread's exit status. (Joining with a thread is the only way to know that cancellation has completed.)
A thread using pthread can have following cancelling statuses:
PTHREAD_CANCEL_ENABLE
PTHREAD_CANCEL_DISABLE
If you try to cancel a thread you do not 100% know if the thread will really get cancelled. Using a join delivers the information to you if the thread was really cancelled or not. There are also cancel types to be considered and respective pthread functions for setting the cancel type and state:
int pthread_setcancelstate (int state, int *oldstate);
int pthread_setcanceltype (int type, int *oldtype);
Here is a sample code borrowed from http://www.ijon.de/comp/tutorials/threads/cancel.html
EDIT: Either I am too stupid to post a few lines of code or the formatter is really going on my nerves today. Just look up the code in the link above, please.
If something goes wrong in a thread or it is stopped from with in somehow it will always be tidied up by the OS. So it's all nice and safe.
You only need to join the thread if you have to be sure it has actually stopped executing, like merging two parallel tasks. (E.g. if you have various threads working on various parts a split structure you need to join them all, as in wait until they are all finished, when you want to combine the structure again)

Stopping an MFC thread

I understand the problem with just killing the thread directly (via AfxEndThread or other means), and I've seen the examples using CEvent objects to signal the thread and then having the thread clean itself up. The problem I have is that using CEvent to signal the thread seems to require a loop where you check to see if the thread is signaled at the end of the loop. The problem is, my thread doesn't loop. It just runs, and the processing could take a while (which is why I'd like to be able to stop it).
Also, if I were to just kill the thread, I realize that anything I've allocated will not have a chance to clean itself up. It seems to me like any locals I've been using that happen to have put stuff on the heap will also not be able to clean themselves up. Is this the case?
There is no secret magic knowledge here.
Just check the event object periodically throughout the function code, where you deem it is safe to exit.
Does your thread ever exit? If so, you could set an event in the thread at exit and have the main process wait for that event via waitforsingleevent. This is best to do with a timeout so the main process doesn't appear to lockup when it's closing. At the timeout event, kill the thread via AfxKillThread. You'll have to determine what a reasonable timeout is, though.
Since you don't loop in the thread this seems to me to be the only way to do this. Of course, you could something like set a boolean flag in the main process and have the thread periodically check this flag, but then your thread code will be littered with "if(!canRun) return;" type code.
If the thread never exits, then AfxKillThread/AfxTerminateThread is the only way to stop the thread.
Locals would be placed on the stack and, hence, WOULD be freed on forcing the thread shut (I think). Destructors won't get called though and any critical sections the thread holds will not get released.
If the thread is ONLY doing things with simple data types on the stack, however, it IS a safe thing to be doing.

Atomic Operation C++

In C++, Windows platform, I want to execute a set of function calls as atomic so that execution doesn't switches to other threads in my process. How do I go about doing that? Any ideas, hints?
EDIT: I have a piece of code like:
someObject->Restart();
WaitForSingleObject(handle, INFINITE);
Now the Restart() function does its work asynchronously, so it returns quickly and when that someObject is restarted it sends me an event from another thread where I signal the event handle on which I'm waiting and thus continue processing. But now the problem is that before the code reaches WaitForSingleObject() part, I receive the restart completion event and I signal the event and after that WaitForSingleObject() never returns since it is not signaled again. That's why I want to execute both Restart() and WaitForSingleObject() as atomic.
This is generally not possible. You can't force the OS to not switch to other threads.
What you can do is one of the following:
Use locks, mutexes, criticals sections or semaphores to synchronize a handful of threads that touch the same data.
Use basic operations that are atomic such as compare-and-exchange or atomic-add in the form of win32 api calls such as InterlockedIncrement() and InterlockedCompareExchange()
You don't want all threads to wait, you just want to wait for the new thread to be done, without the risk of missing the signal. This can be done using a semaphore.
Create a semaphore known by both this code and the code eventually executed by Restart, using CreateSemaphore(NULL,0,1,NULL).
In the code you've shown, you'll still use WaitforSingleObject to wait for your semaphore. When the thread executing the Release code is done with it's work, have it call ReleaseSemaphore.
If ReleaseSemaphore is called first, WaitforSingleObject will let you pass immediately. If WaitforSingleObject is called first, it will wait for ReleaseSemaphore.
MSDN should also help you.
A general solution to lost event race is a counting semaphore.
Are you using PulseEvent() to signal your handle? If so, that's the problem.
According to MSDN,
If no threads are waiting, or if no
thread can be released immediately,
PulseEvent simply sets the event
object's state to nonsignaled and
returns.
So if the handle is signaled before you wait on it, the handle is placed immediately in the nonsignaled state by PulseEvent(). That would appear to be why your are "missing" the event. To correct this, replace PulseEvent() with SetEvent().
With this scenario, though, you may need to reset the event after the wait is complete. This of course depends on if this code is executed more than once during the lifetime of your application. Assuming your waiting thread is the only thread that is waiting on the handle, use CreateEvent() to create an auto reset event. This will automatically reset the handle after your waiting thread is released, making it automatically available for the next time through.
Well, you could suspend (using SuspendThread) all other threads in the process, but I suppose you should rethink design of your program.
This is very easy to fix. Just make sure that the event is the auto-reset event (see the parameters of the CreateEvent) and only call SetEvent to the event handle, never call ResetEvent or PulseEvent or some other things. So the WaitForSingleObject will always return properly. If the event has been already set, the WaitForSingleObject will return immediately and reset the event.
Although I worry about your design in general (ie you are making concurrent tasks sequential, thus losing all the benefits of the hard work to make it concurrent), I think I see the simple solution.
Change your event handle to be MANUAL RESET instead of AUTORESET. (see CreateEvent).
Then you won't miss the signal.
After WaitForSingleObject(...), call ResetEvent().
EDIT:
forget what I just said. That won't work. see comments below.

In wxwidgets, how do I make one thread wait for another to complete before proceeding?

I have a system where my singleton class spawns a thread to do a calculation. If the user requests another calculation while another calculation is still running, I want it to tear down the existing thread and start a new one. But, it should wait for the first thread to exit completely before proceeding. I have all the tear down working but I seem to have an issue with making sure that only one thread runs. My approach is for the StartCalculation function to call mutex->Lock(). And the thread in the destructor releases the lock. It's not working. Am I right in assuming that if Lock() can't get the lock, it spins and keeps trying to reacquire the lock? Can this Lock() be called from my main application thread? Any ideas is helpful. Maybe wxMutex locks are the right mechanism for this.
To wait for a thread you need to create it joinable and simply use wxThread::Wait(). However I agree with the remark above: this is not something you'd normally do at all and definitely not from the main GUI thread as you should never block in it because this freezes the UI.
Consider using a message queue to simply tell the existing thread about the new task it needs to perform instead.