Local static variables and multithreading

  • Thread starter Marcin Kalicinski
  • Start date
M

Marcin Kalicinski

I'm trying to write platform-independent code that will work correctly in
multithreaded environment. I know C++ standard says nothing about threads,
but I still think my question is not entirely off-topic here:

int f()
{
static int n = g();
return n;
}

If I call the above function from multiple threads, can I still assume that
g() will only be called once? Or is it platform dependent?

thank you,
Marcin
 
J

John Carson

Marcin Kalicinski said:
I'm trying to write platform-independent code that will work
correctly in multithreaded environment. I know C++ standard says
nothing about threads, but I still think my question is not entirely
off-topic here:
int f()
{
static int n = g();
return n;
}

If I call the above function from multiple threads, can I still
assume that g() will only be called once?

No.

http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx

Or is it platform dependent?

I suspect the answer is no on any multithreaded platform.
 
A

abelikoff

In order to guarantee the above, the compiler would need to be aware of
threads. It would actually need to generate code to handle that
assignment inside a mutex or a critical section. C++ doesn't do that
(yet).

The code above can exhibit a number of nasty bugs: from duplicate
invocation of g() to use of partially initialized n.

-- Sasha
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,150
Latest member
MakersCBDReviews
Top