Acess variable that was set by thread

Steven Schveighoffer schveiguy at gmail.com
Mon Aug 8 20:36:34 UTC 2022


On 8/8/22 4:04 PM, ag0aep6g wrote:
> On Monday, 8 August 2022 at 19:33:14 UTC, Steven Schveighoffer wrote:
>> There's nothing clever. If you want to access C globals, you should 
>> use `__gshared`, because that's what it is. Using `shared`, isn't 
>> going to save you at all.
> 
> Yes, using `shared` does save you.
> 
> C might not have a `shared` qualifier, but C programmers still have to 
> think about thread-safety. Calling a C function or accessing a C global 
> always comes with some (possibly implied) contract on how to do it 
> safely from multiple threads (the contract might be: "don't").
> 
> `shared` (with `-preview=nosharedaccess`) forces you to think about what 
> the contract is. `__gshared` doesn't.

shared gives you a sense that the language is helping you prevent 
problems. Again, if C isn't playing ball, this is a lie.

> 
> [...]
>> Using `__gshared` to share data with C is as safe as using 
>> `-boundscheck=on` and sending the array into C which has no such 
>> restrictions.
> 
> No it's not. C always being unsafe is true but irrelevant. The point is 
> what you can/can't do on the D side.
> 
> `-boundscheck=on` - Can't easily mess up on the D side. C side can still 
> mess up.
> `-boundscheck=off` - Can easily mess up on the D side.
> `shared` - Can't easily mess up on the D side. C side can still mess up.
> `__gshared` - Can easily mess up on the D side.

Bounds are defined the same in both C and D -- you have a pointer and a 
size, and you can't exceed that size. Yes, the data is conveyed 
differently, but this is trivial to understand and use.

`shared` doesn't fix anything on the D side. All sides must use the same 
mechanism to synchronize data. And there is no standard for 
synchronizing data.

Consider if the proper way to use such a variable is to call 
`properlyUse(int *)`, it won't accept a `shared int *`. Now you are 
doubly-sure to mess up using it specifically because it's marked `shared`.

-Steve


More information about the Digitalmars-d-learn mailing list