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  * Port to the D programming language:
11  *     Frank Benoit <benoit@tionex.de>
12  *******************************************************************************/
13 module org.eclipse.swt.internal.Lock;
14 
15 import java.lang.all;
16 import java.lang.Thread;
17 
18 version(Tango){
19     import tango.core.sync.Mutex;
20     import tango.core.sync.Condition;
21 } else { 
22     import java.nonstandard.sync.mutex;
23     import java.nonstandard.sync.condition;
24 }
25 
26 /**
27  * Instance of this represent a recursive monitor.
28  */
29 public class Lock {
30     int count, waitCount;
31     Thread owner;
32     Mutex mutex;
33     Condition cond;
34 
35     public this() {
36         mutex = new Mutex;
37         cond = new Condition(mutex);
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     synchronized (mutex) {
48         Thread current = Thread.currentThread();
49         if (owner !is current) {
50             waitCount++;
51             while (count > 0) {
52                 try {
53                     cond.wait();
54                 } catch (SyncException e) {
55                     /* Wait forever, just like synchronized blocks */
56                 }
57             }
58             --waitCount;
59             owner = current;
60         }
61         return ++count;
62     }
63 }
64 
65 /**
66  * Unlocks the monitor. If the current thread is not
67  * the monitor owner, do nothing.
68  */
69 public void unlock() {
70     synchronized (mutex) {
71         Thread current = Thread.currentThread();
72         if (owner is current) {
73             if (--count is 0) {
74                 owner = null;
75                 if (waitCount > 0) cond.notifyAll();
76             }
77         }
78     }
79 }
80 }