Skip to content

Commit 817164e

Browse files
committed
new synchronization problems
1 parent 8e86937 commit 817164e

File tree

8 files changed

+582
-12
lines changed

8 files changed

+582
-12
lines changed

synchronization/src/main/java/mk/ukim/finki/os/synchronization/exam14/march/ca3n2/CalciumNitride.java

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -52,22 +52,27 @@ public void execute() throws InterruptedException {
5252
caNum++;
5353
if (caNum == 3) {
5454
// tret ca atom
55-
caNum = 0;
5655
lock.release();
5756
nHere.acquire(2);
58-
ready.release(4);
59-
state.bond();
60-
bondingDone.acquire(4);
61-
canLeave.release(4);
62-
state.validate();
57+
ready.release(5);
58+
} else {
59+
// prv i vtor ca atom
60+
lock.release();
61+
}
62+
ready.acquire();// x2 ca atoms
63+
state.bond();
64+
bondingDone.release();
65+
lock.acquire();
66+
caNum--;
67+
if (caNum == 0) {
68+
// tret ca atom
69+
lock.release();
70+
bondingDone.acquire(5);
71+
n.release(2);
6372
ca.release(3);
6473
} else {
6574
// prv i vtor ca atom
6675
lock.release();
67-
ready.acquire();// x2 ca atoms
68-
state.bond();
69-
bondingDone.release();
70-
canLeave.acquire();
7176
}
7277
}
7378

@@ -86,8 +91,7 @@ public void execute() throws InterruptedException {
8691
ready.acquire(); // x2 n atoms
8792
state.bond();
8893
bondingDone.release();
89-
canLeave.acquire();
90-
n.release();
94+
9195
}
9296

9397
}
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
package mk.ukim.finki.os.synchronization.exam18.backup;
2+
3+
import java.util.*;
4+
import java.util.concurrent.Semaphore;
5+
6+
/**
7+
* @author Riste Stojanov
8+
*/
9+
public class MainG2 {
10+
11+
/**
12+
* Don't change this method
13+
*
14+
* @return
15+
*/
16+
private static final List<DistanceVectorRouter> initNetwork() {
17+
List<DistanceVectorRouter> routers = new ArrayList<>();
18+
19+
DistanceVectorRouter first = new DistanceVectorRouter("X1");
20+
DistanceVectorRouter second = new DistanceVectorRouter("X2", first);
21+
DistanceVectorRouter third = new DistanceVectorRouter("X3", first);
22+
routers.add(first);
23+
routers.add(second);
24+
routers.add(third);
25+
for (int i = 3; i < 10; i++) {
26+
DistanceVectorRouter next = new DistanceVectorRouter("X" + i, first, second, third);
27+
first = second;
28+
second = third;
29+
third = next;
30+
routers.add(next);
31+
}
32+
for (DistanceVectorRouter router : routers) {
33+
System.out.println(router + "\n\t" + router.neighbors + "\n\t" + router.routingTable);
34+
}
35+
return routers;
36+
}
37+
38+
/**
39+
* Finish the todo requirements
40+
*
41+
* @param args
42+
* @throws InterruptedException
43+
*/
44+
public static void main(String[] args) throws InterruptedException {
45+
46+
List<DistanceVectorRouter> routers = initNetwork();
47+
List<Thread> threads = new ArrayList<>();
48+
49+
for (DistanceVectorRouter router : routers) {
50+
// todo: run this in background
51+
Thread t = new Thread(() -> router.keepAliveHartBeat());
52+
threads.add(t);
53+
t.start();
54+
55+
// todo: run this in other thread
56+
Thread t1 = new Thread(() -> router.handleChangesInBackground());
57+
threads.add(t1);
58+
t1.start();
59+
}
60+
61+
// todo: wait for 10_000 ms and terminate all routers
62+
Thread.sleep(10_000);
63+
for (Thread thread : threads) {
64+
thread.interrupt();
65+
}
66+
System.out.println("DONE!");
67+
68+
}
69+
}
70+
71+
class DistanceVectorRouter {
72+
73+
final Set<DistanceVectorRouter> neighbors = new HashSet<>();
74+
final Map<String, Integer> routingTable = new HashMap<>();
75+
private final Queue<Map<String, Integer>> advertisements = new LinkedList<>();
76+
private final String network;
77+
boolean routingTableChanged = false;
78+
private Semaphore hasMessage = new Semaphore(0);
79+
80+
/**
81+
* Don't change this method
82+
*
83+
* @param neighbors
84+
*/
85+
public DistanceVectorRouter(String network, DistanceVectorRouter... neighbors) {
86+
this.network = network;
87+
this.routingTable.put(network, 1);
88+
for (DistanceVectorRouter neighbor : neighbors) {
89+
neighbor.neighbors.add(this);
90+
this.neighbors.add(neighbor);
91+
this.routingTable.put(neighbor.network, 1);
92+
}
93+
}
94+
95+
/**
96+
* Don't change this method
97+
*
98+
* @param invoker
99+
*/
100+
public void notifyNeighbors(String invoker) {
101+
for (DistanceVectorRouter neighbor : neighbors) {
102+
System.out.println(invoker + " " + network + " notifying " + neighbor.network);
103+
neighbor.notifyAdvertisement(routingTable);
104+
}
105+
}
106+
107+
public void notifyAdvertisement(Map<String, Integer> routingTable) {
108+
synchronized (advertisements) {
109+
advertisements.add(routingTable);
110+
hasMessage.release();
111+
}
112+
}
113+
114+
/**
115+
* Don't change this method
116+
*/
117+
public void keepAliveHartBeat() {
118+
Thread.currentThread().setName("keep alive [" + network + "]: ");
119+
try {
120+
notifyNeighbors("keep alive");
121+
Thread.sleep(5000);
122+
notifyNeighbors("keep alive");
123+
} catch (InterruptedException e) {
124+
System.out.println(Thread.currentThread().getName() + " interrupted");
125+
}
126+
}
127+
128+
/**
129+
* TODO: finish this method
130+
*/
131+
public void handleChangesInBackground() {
132+
try {
133+
Thread.currentThread().setName("handle changes [" + network + "]: ");
134+
while (true) {
135+
routingTableChanged = false;
136+
// todo: wait for message from the neighbors
137+
hasMessage.acquire();
138+
synchronized (advertisements) {
139+
// todo: only one call at a given time is allowed for the nextAdvertisement() method
140+
Map<String, Integer> advertisement = advertisements.poll();
141+
142+
calculateRoutingTable(advertisement);
143+
}
144+
145+
if (routingTableChanged) {
146+
System.out.println("new routing table: " + routingTable);
147+
notifyNeighbors("\t\thandle changes");
148+
}
149+
}
150+
} catch (InterruptedException e) {
151+
System.out.println(Thread.currentThread().getName() + " interrupted");
152+
}
153+
}
154+
155+
/**
156+
* Don't change this method
157+
*
158+
* @param advertisement
159+
*/
160+
private final void calculateRoutingTable(Map<String, Integer> advertisement) {
161+
System.out.println(Thread.currentThread().getName() + " calculating routing table");
162+
synchronized (advertisement) {
163+
advertisement.forEach((net, price) -> {
164+
Integer oldPrice = routingTable.get(net);
165+
if (oldPrice == null || (price + 1) < oldPrice) {
166+
synchronized (routingTable) {
167+
routingTable.put(net, price + 1);
168+
}
169+
routingTableChanged = true;
170+
}
171+
});
172+
}
173+
}
174+
175+
@Override
176+
public boolean equals(Object obj) {
177+
if (obj instanceof DistanceVectorRouter)
178+
return network.equals(((DistanceVectorRouter) obj).network);
179+
return false;
180+
}
181+
182+
@Override
183+
public String toString() {
184+
return network;
185+
}
186+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package mk.ukim.finki.os.synchronization.exam18.s3;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.Random;
6+
7+
public class EventProcessor {
8+
9+
public static Random random = new Random();
10+
static List<EventGenerator> scheduled = new ArrayList<>();
11+
12+
public static void main(String[] args) throws InterruptedException {
13+
List<EventProcessor> processors = new ArrayList<>();
14+
// TODO: kreirajte 20 Processor i startuvajte gi vo pozadina
15+
for (int i = 0; i < 20; i++) {
16+
EventProcessor p = new EventProcessor();
17+
processors.add(p);
18+
//TODO: startuvajte go vo pozadina
19+
}
20+
21+
for (int i = 0; i < 100; i++) {
22+
EventGenerator eventGenerator = new EventGenerator();
23+
//TODO: startuvajte go eventGenerator-ot
24+
25+
}
26+
27+
28+
for (int i = 0; i < 20; i++) {
29+
EventProcessor p = processors.get(i);
30+
// TODO: Cekajte 20000ms za Processor-ot p da zavrsi
31+
32+
// TODO: ispisete go statusot od izvrsuvanjeto
33+
}
34+
}
35+
36+
37+
public static void process() {
38+
// TODO: pocekajte 5 novi nastani
39+
40+
System.out.println("processing event");
41+
}
42+
43+
}
44+
45+
46+
class EventGenerator {
47+
48+
public Integer duration;
49+
50+
public EventGenerator() throws InterruptedException {
51+
this.duration = EventProcessor.random.nextInt(1000);
52+
}
53+
54+
55+
/**
56+
* Ne smee da bide povikan paralelno kaj poveke od 5 generatori
57+
*/
58+
public static void generate() {
59+
System.out.println("Generating event: ");
60+
}
61+
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
Event Processing Simulation
2+
============================
3+
4+
Потребно е да извршите симулација за процесирање на настани со дефининираните
5+
класи `EventGenerator` и `Processor` кои треба да функционираат како thread-ови.
6+
7+
Главниот метод `Processor.main` да стартува 20 `Processor` thread-ови и потоа треба да стартува 100 нови `EventGenerator`
8+
thread-ови во позадина. Потоа `main` методот треба да ги чека `Processor` thread-овите да завршат за најмногу 20000ms.
9+
Доколку не завршат за ова време, треба да се прекинат и да се испише порака `Terminated processing`, а во спротивен
10+
случај да се испише `Finished processing`.
11+
12+
13+
Секој од `EventGenerator` thread-овите веднаш по стартувањето во позадина да заспие рандом време со
14+
`Thread.sleep(this.duration)`, по што треба да го генерира настанот со методот `generate()` кој **не смее** да се извршува
15+
паралелно кај **повеќе од 5 генератори**. Потоа треба да се извести `Processor` thread-от дека има нов настан за процесирање.
16+
Додека не заврши ова процесирање, не смеат да се генерираат нови настани.
17+
18+
Секоја од `Processor` класите е Thread, кој во позадина чека да биде известен за **5 нови настани**,
19+
по што ги процесира со користење на методот `process()`. Дури откако ќе заврши овој метод, може да се продолжи со
20+
генерирање на нови настани, а во меѓувреме сите `EventGenerator`-и го чекаат овој метод да заврши.
21+
22+
Вашата задача е да го дополните дадениот код според барањата на задачата, при што треба да внимавате
23+
не настане Race Condition и Deadlock.
24+
25+
```
26+
27+
import java.util.ArrayList;
28+
import java.util.List;
29+
import java.util.Random;
30+
31+
public class EventProcessor {
32+
33+
public static Random random = new Random();
34+
static List<EventGenerator> scheduled = new ArrayList<>();
35+
36+
public static void main(String[] args) throws InterruptedException {
37+
List<EventProcessor> processors = new ArrayList<>();
38+
// TODO: kreirajte 20 Processor i startuvajte gi vo pozadina
39+
for (int i = 0; i < 20; i++) {
40+
EventProcessor p = new EventProcessor();
41+
processors.add(p);
42+
//TODO: startuvajte go vo pozadina
43+
}
44+
45+
for (int i = 0; i < 100; i++) {
46+
EventGenerator eventGenerator = new EventGenerator();
47+
//TODO: startuvajte go eventGenerator-ot
48+
49+
}
50+
51+
52+
for (int i = 0; i < 20; i++) {
53+
EventProcessor p = processors.get(i);
54+
// TODO: Cekajte 20000ms za Processor-ot p da zavrsi
55+
56+
// TODO: ispisete go statusot od izvrsuvanjeto
57+
}
58+
}
59+
60+
61+
public static void process() {
62+
// TODO: pocekajte 5 novi nastani
63+
64+
System.out.println("processing event");
65+
}
66+
67+
}
68+
69+
70+
class EventGenerator {
71+
72+
public Integer duration;
73+
74+
public EventGenerator() throws InterruptedException {
75+
this.duration = EventProcessor.random.nextInt(1000);
76+
}
77+
78+
79+
/**
80+
* Ne smee da bide povikan paralelno kaj poveke od 5 generatori
81+
*/
82+
public static void generate() {
83+
System.out.println("Generating event: ");
84+
}
85+
}
86+
```
87+

0 commit comments

Comments
 (0)