[ILUG] Test-and-set in C/C++
Brian Foster
blf at blf.utvinternet.co.uk
Fri Oct 1 19:00:06 IST 2004
| Date: Fri, 01 Oct 2004 10:56:01 +0100
| From: Vincent Cunniffe <vincent at cunniffe.net>
|
| I've been unable to find any way of doing a proper test-and-set
| [ atomic instruction ] in C/C++. anyone know a way of doing this?
yes.
you cannot.
not in _portable_ C anyways.
there is no way, none, nothing, nil, nana, of writing
any form of an atomic read-modify-write in de jour
(ISO) standard conformant portable C (or C++, AFAIK).
this always has to be done with machine-specific code,
usually assembler, such as the hint/example someone
posted previously --- which was specific to the x86
(I think) _and_ GNU gcc(1). that sort of specificity
is very common.
some people think/claim that the following (or similar)
is always atomic:
volatile int x; /* type as appropriate */
...
if (x++ == 42) {
/* false claim: read 42 and wrote 43 (correct),
* and must have done so atomically (WRONG!).
*/
...
}
that may be atomic on some machines (I don't know and
certainly wouldn't bet on it!), but it _definitely_ is
_not_ on other machines. and it is Ok for it not to be,
since <volatile> does not mandate any read-modify-write
access (nor un-cached access, the other myth); only that
that accesses are non-speculative, in-order, and precise.
cheers!
-blf-
--
«How many surrealists does it take to | Brian Foster Montpellier,
change a lightbulb? Three. One calms | blf at utvinternet.ie FRANCE
the warthog, and two fill the bathtub | Stop E$$o (ExxonMobile)!
with brightly-colored machine tools.» | http://www.stopesso.com
More information about the ILUG
mailing list