Click to See Complete Forum and Search --> : Generic Event implementation (UNIX SetEvent() equivalent)


earl
July 9th, 2005, 09:02 AM
I'm working on porting a generic event class that currently uses the Win32 CreateEvent()/SetEvent()/WaitForSingleObject() functions as the wait and set mechanisms.

It seems I have two choices to implement this in the UNIX world, either pthreads condition values or semaphores. I was initially thinking the condition values would be acceptable, but then it hit me that pthread_cond_signal() might not necessarily behave the way SetEvent() does.

If I call pthread_cond_signal() in one thread, and no threads are waiting, that signal is lost. I *think* the SetEvent() mechanism operates differently in that SetEvent() causes the event to become signaled, even if nobody is currently waiting, so the next thread that waits will immediately get the object and it will be autoreset at that point. Is that accurate (assuming the event was set to be autoreset)?

If that's the case, I think the best bet would be semaphores, because the "event" could be effectively posted ("signaled") even if a waiter thread isn't waiting yet. What I'm not sure about here is whether SetEvent() causes exactly one waiting thread to release, or multiple...? I also lose the functionality provided by pthread_cond_timedwait() if I go this route, although that can probably be roughly implemented in a sem_trywait() loop or something... Any thoughts/ideas on this stuff is appreciated, and any issues I haven't considered as well...

Thanks.

pzavolinsky
July 13th, 2005, 12:22 PM
Hi, I had the same problem some time ago.

It seams that SetEvent does not work as the pthread regular signal but rather like a broadcast (I know there's a broadcast function on pthread conditions).

About the "signal" problem, I finally ended up making an Event class and working with a boolean var (is not the a very clean solution strictly speaking but was the most portable way I could find back then).

Anyway I checked the bool var inside the wait method and depending on it's value issue the actual wait or return immediately. The setevent method would set the bool var as signaled and the resetevent as not signaled.

Obviously if you are not using c++ this solution is out of the question.