01: /*
02: * ThreadLock.java
03: *
04: * Copyright (C) 2004 Peter Graves
05: * $Id: ThreadLock.java,v 1.2 2004/09/09 10:51:15 piso Exp $
06: *
07: * This program is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU General Public License
09: * as published by the Free Software Foundation; either version 2
10: * of the License, or (at your option) any later version.
11: *
12: * This program is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15: * GNU General Public License for more details.
16: *
17: * You should have received a copy of the GNU General Public License
18: * along with this program; if not, write to the Free Software
19: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20: */
21:
22: package org.armedbear.lisp;
23:
24: public final class ThreadLock extends LispObject {
25: private LispThread thread;
26:
27: private void lock() throws ConditionThrowable {
28: LispThread currentThread = LispThread.currentThread();
29: if (!currentThread.equals(thread)) {
30: while (thread != null) {
31: synchronized (this ) {
32: try {
33: wait();
34: } catch (InterruptedException e) {
35: throw new RuntimeException(e);
36: }
37: }
38: }
39: thread = currentThread;
40: }
41: }
42:
43: private void unlock() throws ConditionThrowable {
44: if (thread.equals(LispThread.currentThread())) {
45: synchronized (this ) {
46: thread = null;
47: notifyAll();
48: }
49: }
50: }
51:
52: public String toString() {
53: StringBuffer sb = new StringBuffer("#<THREAD-LOCK @ #x");
54: sb.append(Integer.toHexString(hashCode()));
55: sb.append(">");
56: return sb.toString();
57: }
58:
59: // ### make-thread-lock
60: private static final Primitive0 MAKE_THREAD_LOCK = new Primitive0(
61: "make-thread-lock", PACKAGE_EXT, true) {
62: public LispObject execute() throws ConditionThrowable {
63: return new ThreadLock();
64: }
65: };
66:
67: // ### thread-lock lock
68: private static final Primitive1 THREAD_LOCK = new Primitive1(
69: "thread-lock", PACKAGE_EXT, true) {
70: public LispObject execute(LispObject arg)
71: throws ConditionThrowable {
72: ThreadLock threadLock = (ThreadLock) arg;
73: threadLock.lock();
74: return NIL;
75: }
76: };
77:
78: // ### thread-unlock lock
79: private static final Primitive1 THREAD_UNLOCK = new Primitive1(
80: "thread-unlock", PACKAGE_EXT, true) {
81: public LispObject execute(LispObject arg)
82: throws ConditionThrowable {
83: ThreadLock threadLock = (ThreadLock) arg;
84: threadLock.unlock();
85: return NIL;
86: }
87: };
88: }
|