Re: Is cout << msg an atomic action?
On Feb 4, 11:54 am, Alex Vinokur <ale...@users.sourceforge.net> wrote:
On Feb 4, 11:42 am, James Kanze <james.ka...@gmail.com> wrote:
On Feb 4, 6:17 am,AlexVinokur<ale...@users.sourceforge.net>
wrote:
void foo (int n)
{
std::ostringstream oss;
oss << "ABCD: " << n << std::endl;
std::cout << oss.str() << std::flush;
}
That function has been invoked in multiprocessing mode.
Output was something like:
ABCA: B1
C
etc.
Is cout << msg an atomic action?
It depends on the implementation, but I would not normally
expect to be able to write to the same stream from two different
threads without some external synchronization. Both reading
from and writing to an iostream modify the object itself.
I realize that
cout << msg1 << msg2;
is not an atomic action.
But is
cout << msg1;
also not atomic one?
Define first what you mean by "atomic".
In general, it "modifies" cout. So if any other thread accesses
cout in any way, you need external synchronization of some sort,
at least if the library implements the Posix rules (which as far
as I can tell, also hold under Windows). But it very definitely
depends on the library.
The Rogue Wave library used with Sun CC does give more
guarantees, for example. Nothing useful, of course, but enough
to result in slowing down output by an order of magnitude.
Although not relevant in this example, the g++ library formally
gives less guarantee: as documented, you cannot even call
cout.good() in two different threads without external
synchronization (although in practice, the only time you'll run
into any problems is with string, and then only in a very few
special cases).
The current standard doesn't say anything about threads, so you
can't ask it. The next version will, however, and according to
all likelyhood, will offer the standard Posix guarantee (and no
more).
--
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