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

2 questions: atomic as a fence + typo

renorm
Beginner
508 Views
Hi. I have 2 questions.

1) Atomic as a fence. Writing to an atomic variable has release semantics, e.a. operations before the atomic assigment never move over it. Can I use atomic variables as a fence? Is there any guarantee that compiler won't optimize out the unuzed atomic variable in the following code fragment? Should I qualify it as volatile?
[cpp]T* ptr;
ptr = new T(...);
tbb::atomic ptr_atomic;
ptr_atomic = ptr;
/*
 Past this point ptr should be pointing to
 the fully constructed instance of T. Right?
*/[/cpp]

2) Looks like there is a typo in the Tutorial, Chapter 8, Table 13.
x.fetch_and_store(y) does x=y, not y=x.

Thank you,
renorm.
0 Kudos
6 Replies
RafSchietekat
Valued Contributor III
508 Views
Why wouldn't you instead load/acquire the fully constructed instance of T from the same atomic, eliminating ptr except perhaps for local use?
0 Kudos
renorm
Beginner
508 Views
Do you mean something like this
[cpp]tbb::atomic ptr_atomic;
ptr_atomic = new T(...);
/*
 past this point ptr_atomic points to the fully
 constructed instance of T. We can signal all other
 threads that it is OK to use ptr_atomic.
*/[/cpp]
That would work. But the rest of the code uses plain pointers. I can only make the pointer to point to an instance of T.
0 Kudos
RafSchietekat
Valued Contributor III
508 Views
In another thread you can pass around a plain pointer after you have read it from the atomic. Would that work?
0 Kudos
renorm
Beginner
508 Views
Yes it would work. I probably recode the whole thing to use atomic variables. Is there any performance penalty for using atomic pointers instead of plain pointers?
[cpp]tbb::atomic ptr_atomic;
T* ptr;
T t;

*ptr_atomic = t;
// vs
*ptr = t;
/*
 any performance difference?
*/[/cpp]
0 Kudos
RafSchietekat
Valued Contributor III
508 Views
Don't replace those plain pointers: use the atomics only for synchronisation moments.
0 Kudos
renorm
Beginner
508 Views
That makes sense. I changed my code to use atomic to send a message and left the plain pointers unchanged. Looks like everething works well.
0 Kudos
Reply