synchronized/shared associative array .require error
Loara
loara at noreply.com
Sat Sep 3 09:49:54 UTC 2022
On Friday, 2 September 2022 at 19:15:45 UTC, cc wrote:
> ```d
> synchronized class SyncTable(KEY, VAL) {
> private VAL[KEY] table;
> auto require(KEY key) {
> return table.require(key);
> }
> }
>
> auto table = new shared SyncTable!(string, string);
> table.require("abc");
> ```
>
> Fails to compile:
> ```
> // Error: none of the overloads of template `object.require`
> are callable using argument types `!()(shared(string[string]),
> string)`
> ```
>
> Tried casting away shared as a workaround but I assume that
> will cause some kind of TLS catastrophe.
In current version of D language `synchronized` and `shared` are
independent. In particular `shared` should be used only for basic
types like integers for which atomic operations are well defined,
and not for classes.
Anyway if you must send a reference of a `synchronized` class to
a different thread then it's safe to cast `shared` and then
remove it later:
```d
synchronized class A{
...
}
void sendTo(Tid to, A a){
to.send(cast(shared A) a);
}
A receiveA(){
A a;
receive( (shared A sa) { a = cast(A) sa; });
return a;
}
```
Unfortunately there isn't any traits that tells you if a class is
`synchronized` or not, so you can't do a safe template function
for this.
More information about the Digitalmars-d-learn
mailing list