"extern" for the same file leads to wrong result. bug or feature?

U

Uenal Mutlu

If "extern" is specified for a variable which is already in the same cpp file
then the compiler (VS6) creates a new instance of the var in each thread.
Is this a bug or a feature?
Which is standard conform?

Example:

test.cpp:
int gi = 0;

test.cpp (ie. same file)

thread_func(...)
{
extern int gi;
gi++;
//...
}

thread1 starts and exits. gi now 1 as expected.
thread2 starts and exits. gi now has value 1. Shouldn't it be 2 ?

If the "extern" declaration is not used then gi is 2.
Or, if the "extern" declaration is used and gi is moved to another cpp
then too is gi 2.

What's the correct (std conform) behaviour?


// U.Mutlu
 
V

Victor Bazarov

Uenal said:
If "extern" is specified for a variable which is already in the same cpp file
then the compiler (VS6) creates a new instance of the var in each thread.

Threads are not defined by C++ _language_. You will find more information
in comp.programming.threads or in microsoft.public.vc.language.
Is this a bug or a feature?
Unknown.

Which is standard conform?

Nothing. Or both. Threads are not part of the Standard, so whatever
happens is fine by it.
Example:

test.cpp:
int gi = 0;

This declares an object 'gi' that (by default) has external linkage.
test.cpp (ie. same file)

thread_func(...)
{
extern int gi;

This is another declaration of 'gi'. This 'gi' is the same 'gi' as you
declared and defined outside of any function.
gi++;
//...
}

thread1 starts and exits. gi now 1 as expected.
thread2 starts and exits. gi now has value 1. Shouldn't it be 2 ?

Unknown. Threads are not defined by the language.
If the "extern" declaration is not used then gi is 2.
Or, if the "extern" declaration is used and gi is moved to another cpp
then too is gi 2.

What's the correct (std conform) behaviour?

Either. Both. Unknown. The use of threads introduces the conditions
that C++ Standard cannot account for.

V
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top