Member variables in method are null when called as delegate from thread
Steven Schveighoffer
schveiguy at gmail.com
Tue Jan 12 13:52:31 UTC 2021
On 1/11/21 12:26 PM, Arafel wrote:
> Thanks for the detailed explanation! I think this mixing of types and
> storage classes makes a very unfortunate combination:
>
> ```
> import std;
>
> int i = 0;
> shared int j = 0;
>
> struct S {
> int i = 0;
> shared int j = 0;
> }
>
> S s;
>
> void main() {
> i = 1;
> j = 1;
> s.i = 1;
> s.j = 1;
> spawn(&f);
>
> }
>
> void f() {
> assert(i == 0); // Expected
> assert(j == 1); // Expected
> assert(s.i == 0); // Expected
> assert(s.j == 0); // Wait, what?
> }
> ```
>
> I agree that once you know the inner workings it makes sense, but a
> naïve approach might suggest that `s.j` would be... well, shared, just
> like `j`.
It's definitely confusing, if you don't know what shared means in all
contexts.
shared as storage -> put in the shared globals
shared as type -> the thing can be shared between threads.
The second meaning does not mean it's automatically shared, just that
it's shareable.
-Steve
More information about the Digitalmars-d-learn
mailing list