Jump to content
  • Advertisement


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


Thread Synchronization Question

This topic is 6041 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

    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...

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

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
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.

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!