Skip to main content
gamedev.net
🔒 Locked

Thread Synchronization Question

Started by Russell 1 reply 300+ views
Original Post
Russell
Russell
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?
JonStelly
JonStelly
You don''t need to lock at either place. Just call SetEvent().
Shannon Barber
Shannon Barber
Use a manually reset event as well (in case you ever want top shutdown more than one thing using the same exit event)

Otherwise it''ll unsignal after the first wait''er is released.
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.