| 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 dwt.internal.Lock; |
|---|
| 14 |
|
|---|
| 15 |
import tango.core.Thread; |
|---|
| 16 |
import tango.core.sync.Mutex; |
|---|
| 17 |
import tango.core.sync.Condition; |
|---|
| 18 |
|
|---|
| 19 |
/** |
|---|
| 20 |
* Instance of this represent a recursive monitor. |
|---|
| 21 |
*/ |
|---|
| 22 |
public class Lock { |
|---|
| 23 |
int count, waitCount; |
|---|
| 24 |
Thread owner; |
|---|
| 25 |
Mutex mutex; |
|---|
| 26 |
Condition cond; |
|---|
| 27 |
|
|---|
| 28 |
public this() { |
|---|
| 29 |
mutex = new Mutex; |
|---|
| 30 |
cond = new Condition(mutex); |
|---|
| 31 |
} |
|---|
| 32 |
/** |
|---|
| 33 |
* Locks the monitor and returns the lock count. If |
|---|
| 34 |
* the lock is owned by another thread, wait until |
|---|
| 35 |
* the lock is released. |
|---|
| 36 |
* |
|---|
| 37 |
* @return the lock count |
|---|
| 38 |
*/ |
|---|
| 39 |
public int lock() { |
|---|
| 40 |
synchronized (mutex) { |
|---|
| 41 |
Thread current = Thread.getThis(); |
|---|
| 42 |
if (owner !is current) { |
|---|
| 43 |
waitCount++; |
|---|
| 44 |
while (count > 0) { |
|---|
| 45 |
try { |
|---|
| 46 |
cond.wait(); |
|---|
| 47 |
} catch (SyncException e) { |
|---|
| 48 |
/* Wait forever, just like synchronized blocks */ |
|---|
| 49 |
} |
|---|
| 50 |
} |
|---|
| 51 |
--waitCount; |
|---|
| 52 |
owner = current; |
|---|
| 53 |
} |
|---|
| 54 |
return ++count; |
|---|
| 55 |
} |
|---|
| 56 |
} |
|---|
| 57 |
|
|---|
| 58 |
/** |
|---|
| 59 |
* Unlocks the monitor. If the current thread is not |
|---|
| 60 |
* the monitor owner, do nothing. |
|---|
| 61 |
*/ |
|---|
| 62 |
public void unlock() { |
|---|
| 63 |
synchronized (mutex) { |
|---|
| 64 |
Thread current = Thread.getThis(); |
|---|
| 65 |
if (owner is current) { |
|---|
| 66 |
if (--count is 0) { |
|---|
| 67 |
owner = null; |
|---|
| 68 |
if (waitCount > 0) cond.notifyAll(); |
|---|
| 69 |
} |
|---|
| 70 |
} |
|---|
| 71 |
} |
|---|
| 72 |
} |
|---|
| 73 |
} |
|---|