Mercurial > projects > dwt-mac
comparison dwt/internal/Lock.d @ 0:380af2bdd8e5
Upload of whole dwt tree
author | Jacob Carlborg <doob@me.com> <jacob.carlborg@gmail.com> |
---|---|
date | Sat, 09 Aug 2008 17:00:02 +0200 |
parents | |
children | d8635bb48c7c |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:380af2bdd8e5 |
---|---|
1 /******************************************************************************* | |
2 * Copyright (c) 2000, 2005 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 * | |
11 * Port to the D programming language: | |
12 * Frank Benoit <benoit@tionex.de> | |
13 *******************************************************************************/ | |
14 module dwt.internal.Lock; | |
15 | |
16 import tango.core.Thread; | |
17 import tango.core.sync.Mutex; | |
18 import tango.core.sync.Condition; | |
19 import tango.core.Exception; | |
20 | |
21 import dwt.dwthelper.utils; | |
22 | |
23 /** | |
24 * Instance of this represent a recursive monitor. | |
25 */ | |
26 public class Lock | |
27 { | |
28 int count, waitCount; | |
29 Thread owner; | |
30 Mutex mutex; | |
31 Condition cond; | |
32 | |
33 public this () | |
34 { | |
35 mutex = new Mutex; | |
36 cond = new Condition(mutex); | |
37 } | |
38 | |
39 /** | |
40 * Locks the monitor and returns the lock count. If | |
41 * the lock is owned by another thread, wait until | |
42 * the lock is released. | |
43 * | |
44 * @return the lock count | |
45 */ | |
46 public int lock () | |
47 { | |
48 synchronized (mutex) | |
49 { | |
50 Thread current = Thread.getThis(); | |
51 if (owner !is current) | |
52 { | |
53 waitCount++; | |
54 while (count > 0) | |
55 { | |
56 try | |
57 { | |
58 cond.wait(); | |
59 } | |
60 catch (SyncException e) | |
61 { | |
62 /* Wait forever, just like synchronized blocks */ | |
63 } | |
64 } | |
65 --waitCount; | |
66 owner = current; | |
67 } | |
68 return ++count; | |
69 } | |
70 } | |
71 | |
72 /** | |
73 * Unlocks the monitor. If the current thread is not | |
74 * the monitor owner, do nothing. | |
75 */ | |
76 public void unlock () | |
77 { | |
78 synchronized (mutex) | |
79 { | |
80 Thread current = Thread.getThis(); | |
81 if (owner is current) | |
82 { | |
83 if (--count is 0) | |
84 { | |
85 owner = null; | |
86 if (waitCount > 0) | |
87 cond.notifyAll(); | |
88 } | |
89 } | |
90 } | |
91 } | |
92 } |