Repository navigation
Expand file tree
/
Copy pathIndex.ets
More file actions
100 lines (87 loc) · 2.48 KB
/
Copy pathIndex.ets
File metadata and controls
100 lines (87 loc) · 2.48 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
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 === 'Shopper') {
archetype = new Shopper(new ShoppingCart(), 0, 0);
} else {
archetype = new Thread();
}
addFunc(runnable, archetype);
runnable.run();
}
class ShoppingCart {
public syn: Syc = new Syc();
public static staticSyn: Syc = new Syc();
public className: string = 'ShoppingCart';
private itemCount = new SharedNumber(0);
public addItem(): void {
SynStart(this.syn);
this.itemCount.setValue(this.itemCount.getValue() + 1);
console.log('Item added. Total items in cart: ' + this.itemCount.getValue());
SynEnd(this.syn);
}
public removeItem(): void {
SynStart(this.syn);
if (this.itemCount.getValue() > 0) {
this.itemCount.setValue(this.itemCount.getValue() - 1);
console.log('Item removed. Total items in cart: ' + this.itemCount.getValue());
} else {
console.log('No items to remove.');
}
SynEnd(this.syn);
}
public displayCart(): void {
SynStart(this.syn);
console.log('Shopping Cart contains ' + this.itemCount.getValue() + ' items.');
SynEnd(this.syn);
}
}
class Shopper implements Runnable {
public syn: Syc = new Syc();
public static staticSyn: Syc = new Syc();
public className: string = 'Shopper';
private cart: ShoppingCart;
private addOperations = new SharedNumber();
private removeOperations = new SharedNumber();
constructor(cart: ShoppingCart, addOperations: number, removeOperations: number) {
this.cart = cart;
this.addOperations.setValue(addOperations);
this.removeOperations.setValue(removeOperations);
}
run(): void {
for (let i = 0; i < this.addOperations.getValue(); i++) {
this.cart.addItem();
}
for (let i = 0; i < this.removeOperations.getValue(); i++) {
this.cart.removeItem();
}
}
}
class ShoppingCartSystem {
public syn: Syc = new Syc();
public static staticSyn: Syc = new Syc();
public className: string = 'ShoppingCartSystem';
static main(args: string[]): void {
const cart = new ShoppingCart();
const shopper1 = new Thread(new Shopper(cart, 5, 3));
const shopper2 = new Thread(new Shopper(cart, 3, 2));
shopper1.start();
shopper2.start();
}
}
if (isMainThread()) {
// You can put the entry of your code here to test.
}