aboutsummaryrefslogtreecommitdiffstats
path: root/tests/ajde/examples/spacewar/coordination/Mutex.java
blob: 04ed900d858a552fb5ed8b7a13f91a48e7707f8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package coordination;

import java.lang.String;


class Mutex implements Exclusion {
    String[] methodNames;
    MethodState[] methodStates;

    String prettyName;
  
    Mutex (String[] _methodNames) {
	methodNames = _methodNames;
	methodStates = new MethodState[methodNames.length];
	for (int i = 0; i < methodNames.length; i++) {
	    methodStates[i] = new MethodState();
	}
    }

    private boolean isMethodIn (String _methodName) {
	for (int i = 0; i < methodNames.length; i++) {
	    if (_methodName.equals(methodNames[i])) 
		return(true);
	}
	return(false);
    }

    private MethodState getMethodState (String _methodName) {
	for (int i = 0; i < methodNames.length; i++) {
	    if (_methodName.equals(methodNames[i])) 
		return(methodStates[i]);
	}
	return(null);
    }

    public boolean testExclusion (String _methodName) {
	Thread ct = Thread.currentThread();
	//
	// Loop through each of the other methods in this exclusion set, to be sure
	// that no other thread is running them.  Note that we have to be careful
	// about selfex.
	// 
	for (int i = 0; i < methodNames.length; i++) {
	    if (!_methodName.equals(methodNames[i])) {
		if (methodStates[i].hasOtherThreadThan(ct))
		    return(false);
	    }
	}
	return (true);
    }

    public void enterExclusion (String _methodName) {
	MethodState methodState = getMethodState(_methodName);
	methodState.enterInThread(Thread.currentThread());
    }

    public void exitExclusion (String _methodName) {
	MethodState methodState = getMethodState(_methodName);
	methodState.exitInThread(Thread.currentThread());
    }

    public void printNames() {
	System.out.print("Mutex names: ");
	for (int i = 0; i < methodNames.length; i++)
	    System.out.print(methodNames[i] + " ");
	System.out.println();
    }
}