Intel® oneAPI Threading Building Blocks
Ask questions and share information about adding parallelism to your applications when using this threading library.
2465 Discussions

Implementing Cond variable using atomic operations

shay86
Beginner
678 Views
I'm using atomic operations to implement mutex and cond (i'm currenting using threadpool using posix threads and now need to move to tbb).
For example i'm doing something like this:

Lock_mutex (mutex * m){

while (T&S(TS_Object *) m);

}

Unlock_mutex(mutex *m){

Reset((TS_Object *) m)

}

(this is just pseudo code, the param is actually an atomic operation).
My problem is with implementing pthread_cond_wait and pthread_cond_signal
using only T&S or C&S.
Can anyone directs me please?
Thanks in advanced,
Shay.
0 Kudos
9 Replies
shay86
Beginner
678 Views
This is actually the functions for T&S:

T&S (T&S_object * TS)

{

If (TS.flag==false) {

TS.flag = true;

return false;

} else return true;

}

Reset (T&S_object * TS)

{

TS.flag=false;

}

0 Kudos
Dmitry_Vyukov
Valued Contributor I
678 Views
Real-world condition variables usually block threads. Blocking can't be implemented with atomic operations.
If you need only a toy implementation, then you can implement wait() as unlock-yield-lock, and signal() as no op. No need for atomic operations either.


0 Kudos
shay86
Beginner
678 Views
Thanks for the really fast reply,
i'm not familiar with unlock-yield-lock, can you link me to a code example maybe?
and also, how can i signal other threads in my threadpool that a job is done if i made this function no op?
Thanks.
0 Kudos
Dmitry_Vyukov
Valued Contributor I
678 Views
> i'm not familiar with unlock-yield-lock, can you link me to a code example maybe?

void condvar_wait(mutex* m)
{

Unlock_mutex(m);

pthread_yield()/SwitchToThread();

Lock_mutex(m);

}

void condvar_signal/broadcast()
{
}


0 Kudos
Dmitry_Vyukov
Valued Contributor I
678 Views
> and also, how can i signal other threads in my threadpool that a job is done if i made this function no op?

Since threads are not blocked, there is no need to signal them - they are always ready notice any state change.


0 Kudos
shay86
Beginner
678 Views
Excellent, thanks a lot.
Is there anequivalent for pthread_yield in tbb's library?
or i should implement one myself?
Thanks.
0 Kudos
Dmitry_Vyukov
Valued Contributor I
678 Views
Quoting shay86
Excellent, thanks a lot.
Is there anequivalent for pthread_yield in tbb's library?
or i should implement one myself?
Thanks.

tbb::this_tbb_thread::yield() in

0 Kudos
RafSchietekat
Valued Contributor III
678 Views

Has anyone tried emulating condition variables with dummy child tasks and continuations?

0 Kudos
Vladimir_P_1234567890
678 Views
don't you want to use tbb's condition variable?
--Vladimir
0 Kudos
Reply