James Zappia said:
I assume you mean boost::timed_mutex::scoped_timed_lock lock(mutex,xt) because I don't see a constructor that takes only a timed_mutex.
Yep. Typo. Sorry.
That said, I agree that your way of doing it is better. Above you asked why I continue to use the syntax I do for locking the mutex in the thread. I want to immediately lock it, then in the main thread try to lock it for a finite amount of time. I can't do that with scoped_lock. Perhaps my strategy is wrong. I want to run a thread for only a specified amount of time. I can't afford to block on a join() to wait for that thread to finish.
I don't follow this. The test_thread can use a scoped_lock, while the main thread uses a scoped_timed_lock. There's no reason to use the scoped_timed_lock constructor which forces a non-timed lock in test_thread. As for not being able to wait on a join... why not? What do you expect to happen if you don't join?
3) Is there a way I can cancel a thread if going out of scope doesn't stop it?
Not yet, but there will be. However, I'm not sure that what you want to do is really to cancel the thread. It's hard to tell from this toy example.
What the application does is run a job (thread) that has a finite amount of time to finish. If it doesn't finish in that time it needs to send an alert and explicitly terminate the thread (because it can't be blocked with a join() unless it knows the thread is done). As stated above, perhaps my strategy of using the mutex to see if a thread ran in a given amount of time is wrong.
First, it would probably be better to use a condition to wait for an "I'm finished" predicate, if for no other reason than it makes what you're trying to do clearer. Second, arbitrarily killing a thread is nearly always a bad idea, as it can leave the programs invariants in a broken state. The cancellation mechanism that will be added to Boost.Threads uses a cooperative model for this reason. Even with out cancellation support, this should be trivial to implement for your specific case. Third, I can't understand why you'd want to do what you're doing here. Either what the thread does is something that the main thread doesn't have to rely on, so there's no reason to wait at all, or it is something that you have to rely on and MUST wait for the thread to complete (as in call join()) even if you want said thread to complete within a given time frame. Maybe you need to drop the toy example and explain precisely what you want to accomplish here so that I can give better advice. William E. Kempf