A little of coordination for Rosettacode

bearophile bearophileHUGS at lycos.com
Mon Nov 25 03:22:49 PST 2013


This D1 entry needs an update:
http://rosettacode.org/wiki/Metered_concurrency#D

Is someone willing to update it?


import std.stdio, core.thread, std.c.time;

class Semaphore {
     private int lockCnt, maxCnt;

     this(in int count) {
         maxCnt = lockCnt = count;
     }

     void acquire() {
         if (lockCnt < 0 || maxCnt <= 0)
             throw new Exception("Negative Lock or Zero init. 
Lock");
         while(lockCnt == 0)
             Thread.getThis.yield; // Let other threads release 
lock.
         synchronized lockCnt--;
     }

     void release() {
         synchronized
             if (lockCnt < maxCnt)
                 lockCnt++;
             else
                 throw new Exception("Release lock before 
acquire");
     }

     int getCnt() {
         synchronized return lockCnt;
     }
}

class Worker : Thread {
     private static int id = 0;
     private Semaphore lock;
     private int myId;

     this (Semaphore l) {
         super();
         lock = l;
         myId = id++;
     }

     int run() {
         lock.acquire;
         writefln("Worker %d got a lock(%d left).", myId, 
lock.getCnt);
         msleep(2_000); // Wait 2.0 seconds.
         lock.release;
         writefln("Worker %d released a lock(%d left).",
                  myId, lock.getCnt);
         return 0;
     }
}

void main() {
     Worker[10] crew;
     Semaphore lock = new Semaphore(4);

     foreach (ref c; crew)
         (c = new Worker(lock)).start;
     foreach (ref c; crew)
         c.wait;
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list