Archived

This topic is now archived and is closed to further replies.

Thread Synchronization Question

This topic is 5828 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''m writing a thread class for my multithreaded program, and one of the features that I''m aiming for is to be able to shut down the thread once it''s no longer needed. So my solution is to have a handle to an event object in the private data of the class, and when I call the ShutDown() method of the class, do a simple SetEvent() on the event object, which the thread checks periodically with WaitForSingleObject(). My question is how I should go about protecting this event handle, or if I need to at all. Here''s what I''m thinking:
  
// In the ShutDown() member of the thread class

void Thread::ShutDown()
{
    Lock(); // generic locking function for discussion purposes

    SetEvent(exitEventHandle);
    UnLock(); // generic unlocking function

}
  
I should be able to safely call SetEvent() without worrying about the thread polling the event and causing any problems, because I can safely lock it and unlock it, but in the polling for the actual thread function:
  
// ...code here...

Lock();
if(WaitForSingleObject(thread->GetExitEventHandle, 0) != WAIT_TIMEOUT)
{
    // the event is set, time to shut down this thread

}
UnLock();
  
In this section of code, to prevent two threads from accessing the handle at the same time I have the call to Lock() before the WaitForSingleObject call. My question is really whether or not I need to do any data access synchronization when passing kernel object handles to functions like SetEvent or WaitForSingleObject or WaitForMultipleObjects. I think the WaitForSingleObject (or MultipleObjects) calls should be fine with a millisecond parameter of 0, but in another section I have a call like
  
WaitForMultipleObjects(objects, INFINITE);
  
So I would need to obtain a lock before this call, hold on to the lock until after the call, but if I hold onto the lock until after the call, no other thread can set any events because this thread will own the lock, so deadlock occurs. Any advice or solutions to this problem?

Share this post


Link to post
Share on other sites