Re: How to create a volatile std::string?
On Jan 31, 9:24 pm, Chris Thomasson <cris...@comcast.net> wrote:
On Thu, 31 Jan 2008 21:11:10 +0200, Juha Nieminen wrote:
I have some data inside a struct instance in a namespace and
I want to initialize that data before spawning a thread
which will read that data.
[...]
For POSIX and Windows, as long as the data is prepared
_before_ you create a new thread, everything will be rendered
visible and the thread will be able to see a coherent view;
pthread_create(...) acts as a release-membar.
Note that he was talking about std::string with g++. The last
time I looked, g++ did NOT give the Posix guarantees for
std::string, and you did need a lock for all accesses, even if
none modified the string.
See http://gcc.gnu.org/onlinedocs/libstdc++/faq/index.html#5_6,
and in particular, the last paragraph:
All library objects are safe to use in a multithreaded
program as long as each thread carefully locks out
access by any other thread while it uses any object
visible to another thread, i.e., treat library objects
like any other shared resource. In general, this
requirement includes both read and write access to
objects; unless otherwise documented as safe, do not
assume that two threads may access a shared standard
library object at the same time.
Also see bug report 21334.
According to the g++ documentation and guarantees, Juha will
have to acquire a lock each time he accesses his strings,
regardless of the fact that he doesn't modify them. In
practice, given the actual implementation, he will not need the
locks if all of the accesses are through lvalues with const
types, or if he simply takes the precaution of calling the
non-const operator[] once before calling pthread_create.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34