Mercurial > projects > dwt-addons
comparison dwtx/core/internal/jobs/Semaphore.d @ 122:9d0585bcb7aa
Add core.jobs package
author | Frank Benoit <benoit@tionex.de> |
---|---|
date | Tue, 12 Aug 2008 02:34:21 +0200 |
parents | |
children | 862b05e0334a |
comparison
equal
deleted
inserted
replaced
121:c0304616ea23 | 122:9d0585bcb7aa |
---|---|
1 /******************************************************************************* | |
2 * Copyright (c) 2003, 2006 IBM Corporation and others. | |
3 * All rights reserved. This program and the accompanying materials | |
4 * are made available under the terms of the Eclipse Public License v1.0 | |
5 * which accompanies this distribution, and is available at | |
6 * http://www.eclipse.org/legal/epl-v10.html | |
7 * | |
8 * Contributors: | |
9 * IBM Corporation - initial API and implementation | |
10 * Port to the D programming language: | |
11 * Frank Benoit <benoit@tionex.de> | |
12 *******************************************************************************/ | |
13 module dwtx.core.internal.jobs.Semaphore; | |
14 | |
15 import tango.core.Thread; | |
16 import tango.core.sync.Mutex; | |
17 import tango.core.sync.Condition; | |
18 import dwt.dwthelper.utils; | |
19 import dwt.dwthelper.Runnable; | |
20 import tango.text.convert.Format; | |
21 | |
22 public class Semaphore { | |
23 protected long notifications; | |
24 protected Thread runnable; | |
25 | |
26 private Mutex mutex; | |
27 private Condition condition; | |
28 | |
29 public this(Thread runnable) { | |
30 mutex = new Mutex; | |
31 condition = new Condition(mutex); | |
32 this.runnable = runnable; | |
33 notifications = 0; | |
34 } | |
35 | |
36 /** | |
37 * Attempts to acquire this semaphore. Returns true if it was successfully acquired, | |
38 * and false otherwise. | |
39 */ | |
40 public bool acquire(long delay) { | |
41 synchronized(mutex){ | |
42 implMissing( __FILE__, __LINE__ ); | |
43 // DWT | |
44 // if (Thread.interrupted()) | |
45 // throw new InterruptedException(); | |
46 long start = System.currentTimeMillis(); | |
47 long timeLeft = delay; | |
48 while (true) { | |
49 if (notifications > 0) { | |
50 notifications--; | |
51 return true; | |
52 } | |
53 if (timeLeft <= 0) | |
54 return false; | |
55 condition.wait(timeLeft/1000.0f); | |
56 timeLeft = start + delay - System.currentTimeMillis(); | |
57 } | |
58 } | |
59 } | |
60 | |
61 public override int opEquals(Object obj) { | |
62 return (runnable is (cast(Semaphore) obj).runnable); | |
63 } | |
64 | |
65 public override hash_t toHash() { | |
66 return runnable is null ? 0 : (cast(Object)runnable).toHash(); | |
67 } | |
68 | |
69 public void release() { | |
70 synchronized( mutex ){ | |
71 notifications++; | |
72 condition.notifyAll(); | |
73 } | |
74 } | |
75 | |
76 // for debug only | |
77 public String toString() { | |
78 return Format("Semaphore({})", cast(Object) runnable ); //$NON-NLS-1$ //$NON-NLS-2$ | |
79 } | |
80 } |