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

Implementing Cond variable using atomic operations

shay86
Beginner
188 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
188 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;

}

Dmitry_Vyukov
Valued Contributor I
188 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.


shay86
Beginner
188 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.
Dmitry_Vyukov
Valued Contributor I
188 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()
{
}


Dmitry_Vyukov
Valued Contributor I
188 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.


shay86
Beginner
188 Views
Excellent, thanks a lot.
Is there anequivalent for pthread_yield in tbb's library?
or i should implement one myself?
Thanks.
Dmitry_Vyukov
Valued Contributor I
188 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

RafSchietekat
Black Belt
188 Views

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

Vladimir_P_Intel2
188 Views
don't you want to use tbb's condition variable?
--Vladimir
Reply