Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
49
Task/Metered-concurrency/D/metered-concurrency-1.d
Normal file
49
Task/Metered-concurrency/D/metered-concurrency-1.d
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
module meteredconcurrency ;
|
||||
import std.stdio ;
|
||||
import std.thread ;
|
||||
import std.c.time ;
|
||||
|
||||
class Semaphore {
|
||||
private int lockCnt, maxCnt ;
|
||||
this(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++ ; }
|
||||
override int run() {
|
||||
lock.acquire ;
|
||||
writefln("Worker %d got a lock(%d left).", myId, lock.getCnt) ;
|
||||
msleep(2000) ; // wait 2.0 sec
|
||||
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(inout c ; crew)
|
||||
(c = new Worker(lock)).start ;
|
||||
foreach(inout c ; crew)
|
||||
c.wait ;
|
||||
}
|
||||
21
Task/Metered-concurrency/D/metered-concurrency-2.d
Normal file
21
Task/Metered-concurrency/D/metered-concurrency-2.d
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
module metered;
|
||||
|
||||
import tools.threads, tools.log, tools.time, tools.threadpool;
|
||||
|
||||
void main() {
|
||||
log_threads = false;
|
||||
auto done = new Semaphore, lock = new Semaphore(4);
|
||||
auto tp = new Threadpool(10);
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
tp.addTask(i /apply/ (int i) {
|
||||
scope(exit) done.release;
|
||||
lock.acquire;
|
||||
logln(i, ": lock acquired");
|
||||
sleep(2.0);
|
||||
lock.release;
|
||||
logln(i, ": lock released");
|
||||
});
|
||||
}
|
||||
for (int i = 0; i < 10; ++i)
|
||||
done.acquire;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue