[boost.thread] Porting Windows event to boost::condition
I'm porting WinAPI code to boost.thread. Confused converting Windows event to boost::condition... There are two threads, one waiting to another: HANDLE Event; // shared Event = CreateEvent(NULL, TRUE, FALSE, NULL); ... void Thread1() { ResetEvent(Event); MyCode::CreateThread2(); if (WaitForSingleObject(Event, 500 /*ms*/) != WAIT_OBJECT_0) ... } void Thread2() { SetEvent(Event); } My solution looks like this: boost::condition Condition; ... void Thread1() { MyCode::CreateThread2(); boost::mutex m; boost::mutex::scoped_lock l(m); if (!Condition.timed_wait(l, make500msdelay())) ... } void Thread2() { Condition.notify_all(); } Am I using boost::condition right way? Is `m' mutex nessesary? -- Raider
I usually do something like this for that sort of problem. terry boost::mutex Mutex; boost::condition Condition; bool Signalled; void Thread1() { MyCode::CreateThread2(); boost::mutex::scoped_lock l(Mutex); Signalled = false; while (!Signalled) Condition.timed_wait(l, make500msdelay()); } // Thread1 void Thread2() { mutex::scoped_lock(Mutex); Signalled = true; Condition.notify_all(); } // Thread2
Oops, scoped_lock in Thread 2 needs a name.
boost::mutex Mutex; boost::condition Condition; bool Signalled;
void Thread1() { MyCode::CreateThread2(); boost::mutex::scoped_lock lock(Mutex); Signalled = false; while (!Signalled) Condition.timed_wait(lock, make500msdelay()); } // Thread1
void Thread2() { mutex::scoped_lock lockMutex); Signalled = true; Condition.notify_all(); } // Thread2
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Friday 28 March 2008 14:28 pm, Raider wrote:
boost::condition Condition; ...
void Thread1() { MyCode::CreateThread2(); boost::mutex m; boost::mutex::scoped_lock l(m); if (!Condition.timed_wait(l, make500msdelay())) ... }
void Thread2() { Condition.notify_all(); }
Am I using boost::condition right way? Is `m' mutex nessesary?
It looks like you need to lock m in Thread2, to insure the notify doesn't happen before Thread1 starts waiting on it. - -- Frank -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) iD8DBQFH7U8a5vihyNWuA4URAuNFAKCGwsTYBqVewizUOR2o2UcnCKGXwwCdH4Rp UJOLnnuHwqfAJAmvqHcciYs= =MLco -----END PGP SIGNATURE-----
participants (3)
-
Frank Mori Hess
-
Raider
-
Terry G