Repository navigation
Expand file tree
/
Copy pathIndex.ets
More file actions
112 lines (96 loc) · 2.42 KB
/
Copy pathIndex.ets
File metadata and controls
112 lines (96 loc) · 2.42 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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 === 'Producer') {
archetype = new Producer(new SharedBuffer());
} else if (runnable.className === 'Consumer') {
archetype = new Consumer(new SharedBuffer());
} else {
archetype = new Thread();
}
addFunc(runnable, archetype);
runnable.run();
}
class SharedBuffer {
public syn: Syc = new Syc();
public static staticSyn: Syc = new Syc();
public className: string = 'SharedBuffer';
private data = new SharedNumber();
private isEmpty = new SharedBoolean(true);
public produce(newData: number): void {
{
SynStart(this.syn);
this.data.setValue(newData);
this.isEmpty.setValue(false);
console.log('Produced: ' + this.data.getValue());
SynEnd(this.syn);
}
}
public consume(): number {
{
SynStart(this.syn);
if (!this.isEmpty.getValue()) {
console.log('Consumed: ' + this.data.getValue());
this.isEmpty.setValue(true);
}
SynEnd(this.syn);
return this.data.getValue();
}
}
}
class Producer implements Runnable {
public syn: Syc = new Syc();
public static staticSyn: Syc = new Syc();
public className: string = 'Producer';
private buffer: SharedBuffer;
constructor(buffer: SharedBuffer) {
this.buffer = buffer;
}
run(): void {
for (let i = 0; i < 10; i++) {
this.buffer.produce(i);
}
}
}
class Consumer implements Runnable {
public syn: Syc = new Syc();
public static staticSyn: Syc = new Syc();
public className: string = 'Consumer';
private buffer: SharedBuffer;
constructor(buffer: SharedBuffer) {
this.buffer = buffer;
}
run(): void {
for (let i = 0; i < 10; i++) {
this.buffer.consume();
}
}
}
class ProducerConsumerTest {
public syn: Syc = new Syc();
public static staticSyn: Syc = new Syc();
public className: string = 'ProducerConsumerTest';
static main(args: string[]): void {
const buffer = new SharedBuffer();
const producerThread = new Thread(new Producer(buffer));
const consumerThread = new Thread(new Consumer(buffer));
producerThread.start();
consumerThread.start();
}
}
if (isMainThread()) {
// You can put the entry of your code here to test.
}