Repository navigation
Expand file tree
/
Copy pathIndex.ets
More file actions
83 lines (71 loc) · 2.53 KB
/
Copy pathIndex.ets
File metadata and controls
83 lines (71 loc) · 2.53 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { SynStart, SynEnd, wait, notify, SharedBoolean, SharedString, SharedNumber, Syc, isMainThread, addFunc, Runnable, Thread } from './ThreadBridge';
export function sharedWash(runnable: Runnable) {
let archetype: Runnable;
if (runnable.className === "Vehicle") {
archetype = new Vehicle("Archetype Vehicle", new Bridge(1));
} else {
archetype = new Thread();
}
addFunc(runnable, archetype);
runnable.run();
}
class Bridge {
public syn: Syc = new Syc();
public static staticSyn: Syc = new Syc();
public className: string = "Bridge";
private capacity: number;
private vehicles: string[];
private count = new SharedNumber();
private readonly synchronized_object = new Syc();
constructor(capacity: number) {
this.capacity = capacity;
this.vehicles = new Array<string>(capacity);
this.count.setValue(0);
}
public cross(vehicleName: string): void {
SynStart(this.synchronized_object);
while (this.count.getValue() >= this.capacity) {
console.log(`${vehicleName} is waiting to cross the bridge.`);
}
this.vehicles[this.count.getValue()] = vehicleName;
this.count.setValue(this.count.getValue() + 1);
console.log(`${vehicleName} is crossing the bridge.`);
for (let i = 0; i < 1000; i++);
this.count.setValue(this.count.getValue() - 1);
console.log(`${vehicleName} has crossed the bridge.`);
for (let i = 0; i < this.count.getValue(); i++) {
this.vehicles[i] = this.vehicles[i + 1];
}
this.vehicles[this.count.getValue()] = null;
SynEnd(this.synchronized_object);
}
}
class Vehicle implements Runnable {
public syn: Syc = new Syc();
public static staticSyn: Syc = new Syc();
public className: string = "Vehicle";
private name = new SharedString();
private bridge: Bridge;
constructor(name: string, bridge: Bridge) {
this.name.setValue(name);
this.bridge = bridge;
}
run(): void {
this.bridge.cross(this.name.getValue());
}
}
class Car {
public syn: Syc = new Syc();
public static staticSyn: Syc = new Syc();
public className: string = "Car";
public static main(args: string[]): void {
const bridge = new Bridge(2);
for (let i = 1; i <= 5; i++) {
const vehicleThread = new Thread(new Vehicle(`Vehicle ${i}`, bridge));
vehicleThread.start();
}
}
}
if (isMainThread()) {
// You can put the entry of your code here to test.
}