a static local variable in a static method is thread local storage?

  • Thread starter Patrick Hoffmann
  • Start date
P

Patrick Hoffmann

hi folx,

today I had "multithreading" trouble with the following code (MS
VC++6/optimized compiling):

---------------------------
class myclass
{
static int s_nNext;
public:
static int getN() { static int N = s_nNext++; return N; }
};

int myclass::s_nNext = 0;
---------------------------

myclass::getN() increments myclass::s_nNext for one time and returns
it before.
With this code I wanted to create an automatic "class-id-enumeration".
It worked well in a multi threaded enviroment with linux/gcc for a
long time. But today I got problems under VC6++/Windows, because in
this case N seems to be thread local storage. So every thread
(including the main) gets a new id for the same class.

I worked around that problem, but I'm interested in an official
documentation of this issue. Is it part of C++, MS or VC++?

Can anybody give me some acknowlege?

thanx much, keep hack'n!

p@
 
J

Jack Klein

hi folx,

today I had "multithreading" trouble with the following code (MS
VC++6/optimized compiling):

[snip]

You need to take this to one of Microsoft's support groups in the
family. We discuss the C++ language here,
which has no support at all for multithreading or thread local
storage. These are all compiler specific issues.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
 
P

Patrick Hoffmann

Jack Klein said:
You need to take this to one of Microsoft's support groups in the
family. We discuss the C++ language here,
which has no support at all for multithreading or thread local
storage. These are all compiler specific issues.

Ok, this is correct, if MS is the problem. But I'm not sure if this is
right. It also could be an issue of C++ static inline methods. May be
the compiler generates the static local variable N for every call of
f(), because it's static & inline?

p@
 
C

Christian Janßen

class myclass
{
static int s_nNext;
public:
static int getN() { static int N = s_nNext++; return N; }
};

int myclass::s_nNext = 0;

In a multithreading environment your code will generate random results.
"myclass::s_nNext" wont be in TLS under windows,
since you ommited __declspec(thread).

Christian
 

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

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top