Atomic updates

monarch_dodra monarchdodra at gmail.com
Mon Jan 21 13:53:15 PST 2013


On Monday, 21 January 2013 at 21:16:58 UTC, bearophile wrote:
> Some more little changes, I have added counters, and I have 
> used the faster Xorshift:
>
> http://codepad.org/hIFPgSTd
>
> Bye,
> bearophile

I wouldn't mind seeing some "scope" in there. Keeps things safe. 
After all, those locks can throw exceptions... (can't they? I'm 
no mutex expert).

Anyways, something like this:


     public void transfer(in uint from, in uint to,
                          in TBucketValue amount) {
         auto low  = min(from, to);
         auto high = max(from, to);

         buckets[low].mtx.lock();
         scope(exit) buckets[low].mtx.unlock();
         buckets[high].mtx.lock();
         scope(exit) buckets[high].mtx.unlock();

         immutable realAmount = min(buckets[from].value, amount);
         buckets[from].value -= realAmount;
         buckets[to  ].value += realAmount;
     }


     void toString(in void delegate(const(char)[]) sink) {
         TBucketValue sum = 0;
         sink("(");
         size_t i;
         scope(exit) foreach (ref b; buckets[0 .. i]) {
             b.mtx.unlock().collectException();
         }
         foreach (ref b; buckets) {
             b.mtx.lock();
             ++i;
             sum += b.value;
             sink(text(b.value));
             sink(" ");
         }
         sink(") ");
         sink(text(sum));
     }


More information about the Digitalmars-d-learn mailing list