aa.keys, synchronized and shared

torhu torhu at yahoo.com
Thu Nov 10 21:55:26 UTC 2022


I'm trying to make a more thread-safe wrapper for AA's:

```
synchronized final class SyncAA(K, V) ///
{
     ///
     V opIndex(K key) { return data_[key]; }

     ///
     V opIndexAssign(V value, K key) { return data_[key] = value; }

     ///
     K[] keys() const { return data_.keys; }

     ///
     void remove(K key) { data_.remove(key); }

     /// There is no `in` operator, it would not be thread-safe.
     V get(K key, lazy V defaultValue=V.init)
     {
         auto p = key in data_;
         return p ? *p : defaultValue;
     }

     ///
     int opApply(scope int delegate(inout ref V) dg) const
     {
         int result = 0;
         foreach (value; data_) {
             result = dg(value);
             if (result)
                 break;
         }
         return result;
     }

     ///
     int opApply(scope int delegate(K, inout ref V) dg) const
     {
         int result = 0;
         foreach (key, value; data_) {
             result = dg(key, value);
             if (result)
                 break;
         }
         return result;
     }

private:
     V[K] data_;
}
```

In another file:
`__gshared serverListCache = new SyncAA!(string, ServerList);`

I'm using `keys` in a regular function, this is the error i get:

C:\prog\dmd\windows\bin\..\..\src\druntime\import\object.d(3245,36): Error: cannot implicitly convert expression `aa` of type `shared(const(ServerList[string]))` to `const(shared(ServerList)[string])`
src\syncaa.d(17,36): Error: template instance 
`object.keys!(shared(const(ServerList[string])), 
shared(const(ServerList)), string)` error instantiating
src\serveractions.d(45,33):        instantiated from here: 
`SyncAA!(string, ServerList)`
src\serveractions.d(50,17): Error: `shared` `const` method 
`syncaa.SyncAA!(string, ServerList).SyncAA.keys` is not callable 
using a non-shared mutable object
Error C:\prog\dmd\windows\bin\dmd.exe failed with exit code 1.




More information about the Digitalmars-d-learn mailing list