Spot the Bug: Fun Concurrency Bug

  • Thread starter Chris Mullins [MVP - C#]
  • Start date
M

Marc Gravell

As a follow-on question... where does variable i 'live'. It's local
and
a value type, so lives on the local stack...
Nope, it doesn't live on the stack - it is "captured", so it lives as
a field on an object that the C# compiler creates for you. The rules
for the scoping of each "captured" variable is quite tricky... but but
*conceptually* what we are talking about (without using captures)
would be comparable to the following (although the compiler implements
it differently):

class SomeObject {
int i;
void SomeMethod() {
Debug.Assert(i != 2);
}
}
....
SomeObject obj = new SomeObject(); // obj instance is managed
for(int tmp = 0; tmp < 2; tmp ++) { // tmp lives on the stack
obj.i = tmp; // i lives on obj
Thread t = new Thread(obj.SomeMethod);
}

note that there is only a single "obj", and hence all share an "i".
Now compare to the version with a "j" introduced (see my other post in
this topic):

class SomeOtherObject {
int j;
void SomeOtherMethod() {
Debug.Assert(j != 2);
}
}
....
for(int i = 0; i < 2; i++) { // i lives on the stack
SomeOtherObject obj = new SomeOtherObject(); // obj instance is
managed
obj.j = i; // j lives on obj
Thread t = new Thread(obj.SomeOtherObject);
}

in this latter case, each loop iteration gets a different object, and
hence a different "j"

Please note: I have simplified the behavior to make a simple example.

Marc
 
J

Jon Skeet [C# MVP]

As a follow-on question... where does variable i 'live'. It's local and
a value type, so lives on the local stack...

Well, it's only *sort* of a local variable. It's actually a captured
variable, and will live on the heap. It's the fact that it's captured
that makes the whole thing confusing.

Jon
 
M

Mads Bondo Dydensborg

Chris said:
Your explination is dead on, but the boxing / byref behavior of the
variable passed into the Closure is what made this code behavie in a way
other than was expected. I was expecting the int (a value type) to be
passed in by value, and therefore not change...

Actually, this functionality is much more useful. Besides the explanations
given here, this page may be interessting to you:

http://en.wikipedia.org/wiki/Closure_(computer_science)

Regards,

Mads

--
Med venlig hilsen/Regards

Systemudvikler/Systemsdeveloper cand.scient.dat, Ph.d., Mads Bondo
Dydensborg
Dansk BiblioteksCenter A/S, Tempovej 7-11, 2750 Ballerup, Tlf. +45 44 86 77
34
 

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

Top