Acess variable that was set by thread

ag0aep6g anonymous at example.com
Mon Aug 8 13:55:02 UTC 2022


On Monday, 8 August 2022 at 12:45:20 UTC, bauss wrote:
> On Monday, 8 August 2022 at 10:17:57 UTC, ag0aep6g wrote:
>>
>> Never ever use `__gshared` ever.
[...]
> To sum it up:
>
> Single-write/Single-read?
> __gshared
>
> Single-write/Multi-read?
> __gshared
>
> Multi-write/Single-read?
> shared
>
> Multi-write/Multi-read?
> shared

Nope. All of those can be race conditions.

Here's a single-write, single-read one:

```d
align(64) static struct S
{
     align(1):
     ubyte[60] off;
     ulong x = 0;
}
__gshared S s;
void main()
{
     import core.thread: Thread;
     import std.conv: to;
     new Thread(() {
         foreach (i; 0 .. uint.max)
         {
             s.x = 0;
             s.x = -1;
         }
     }).start();
     foreach (i; 0 .. uint.max)
     {
         auto x = s.x;
         assert(x == 0 || x == -1, to!string(x, 16));
     }
}
```

If you know how to access the variable safely, you can do it with 
`shared`.

I maintain: Never ever use `__gshared` ever.


More information about the Digitalmars-d-learn mailing list