Page 1 of 1

[Wish] Condition with wait(), signal(), signalAll()

Posted: Fri Apr 23, 2010 7:40 am
by NicTheQuick
Hi,

I have the wish for conditions to extent the mutex system. It should be similar to pthread_mutex_t and pthread_cond_t from the c++ header 'pthread.h'.
You can find the complete description here and here.

Up to now we have the functions 'LockMutex()' and 'UnlockMutex()' to synchronize threads. But without conditions we can get trouble with implementing the single-writer-multiple-reader-problem. I thought the following functions were useful:

Code: Select all

hCondition.i = CreateCondition() ;creates a new condition
hMutex.i = CreateMutex()
ConditionWait(hCondition, hMutex) ;release the lock and wait for a signal
ConditionSignal(hCondition) ;signals at least one waiting thread. If no thread is waiting: nop
ConditionSignalAll(hCondition); signals all waiting threads.
Before you call ConditionWait(hCondition, hMutex), you have to lock the mutex you want to use. ConditionWait(...) unlocks the mutex and blocks the current thread without a busy wait to save cpu cycles. So an other thread can get the lock, calls ConditionSignal(hCondition) and unlocks the lock. At least one of the waiting threads instantly get this signal and try to lock again. If it gets the lock, it returns from ConditionWait().

You can use conditions for barriers too.

By the way: What's about volatile variables like in C(++)? :wink:

Re: [Wish] Condition with wait(), signal(), signalAll()

Posted: Fri Apr 23, 2010 10:28 am
by ts-soft
What is the difference to Semaphore in PB?

Re: [Wish] Condition with wait(), signal(), signalAll()

Posted: Fri Apr 23, 2010 11:14 am
by NicTheQuick
If there is no condition waiting the ConditionSignal() will become a NOP (no operation). If you have a Semaphore and call SignalSemaphore(), then the internal counter always will be increased by 1, even if there is no waiting semaphore. This results in a problem, if an other thread is calling WaitSemaphore() and the internal counter is greater than 0. Because in this case WaitSemaphore() will not waiting for the next signal. A condition will always wait until you call ConditionSignal() or ConditionSignalAll() after.

Re: [Wish] Condition with wait(), signal(), signalAll()

Posted: Fri Jan 21, 2022 4:10 pm
by NicTheQuick
*push*

This thing is really necessary for proper thread handling.

Re: [Wish] Condition with wait(), signal(), signalAll()

Posted: Fri Jan 21, 2022 8:07 pm
by idle
Could be useful it should be easy enough to implement in a macro with c backend I assume p thread is included on windows and mac

Re: [Wish] Condition with wait(), signal(), signalAll()

Posted: Sat Jan 22, 2022 7:19 pm
by NicTheQuick
I already inplemented this on Linux with pthreads but I wish it was native in Purebasic.