-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2-deadlock.js
More file actions
319 lines (251 loc) · 10.9 KB
/
2-deadlock.js
File metadata and controls
319 lines (251 loc) · 10.9 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// ============================================
// DEADLOCK - Взаимная блокировка
// ============================================
console.log('\n=== DEADLOCK - ПРОБЛЕМА ===\n');
class Mutex {
constructor(name) {
this.name = name;
this.locked = false;
this.queue = [];
}
async lock() {
console.log(`[${Date.now()}] Попытка захвата ${this.name}`);
if (!this.locked) {
this.locked = true;
console.log(`[${Date.now()}] ✓ Захвачен ${this.name}`);
return;
}
console.log(`[${Date.now()}] Ожидание ${this.name}...`);
await new Promise(resolve => this.queue.push(resolve));
console.log(`[${Date.now()}] ✓ Захвачен ${this.name}`);
}
unlock() {
console.log(`[${Date.now()}] Освобожден ${this.name}`);
if (this.queue.length > 0) {
const resolve = this.queue.shift();
resolve();
} else {
this.locked = false;
}
}
}
async function demonstrateDeadlock() {
const mutexA = new Mutex('Mutex-A');
const mutexB = new Mutex('Mutex-B');
async function task1() {
console.log('\n[TASK-1] Начало');
await mutexA.lock();
console.log('[TASK-1] Захватил A, жду немного...');
await new Promise(resolve => setTimeout(resolve, 100));
console.log('[TASK-1] Пытаюсь захватить B...');
await mutexB.lock();
console.log('[TASK-1] Захватил оба мьютекса!');
mutexB.unlock();
mutexA.unlock();
console.log('[TASK-1] Завершено\n');
}
async function task2() {
console.log('\n[TASK-2] Начало');
await mutexB.lock();
console.log('[TASK-2] Захватил B, жду немного...');
await new Promise(resolve => setTimeout(resolve, 100));
console.log('[TASK-2] Пытаюсь захватить A...');
await mutexA.lock();
console.log('[TASK-2] Захватил оба мьютекса!');
mutexA.unlock();
mutexB.unlock();
console.log('[TASK-2] Завершено\n');
}
console.log('Запуск двух задач...');
console.log('Task-1: захватывает A → потом B');
console.log('Task-2: захватывает B → потом A');
console.log('❌ Результат: DEADLOCK!\n');
// Это зависнет навсегда
const timeout = new Promise(resolve =>
setTimeout(() => {
console.log('\n⏰ TIMEOUT: Задачи зависли в deadlock!\n');
resolve();
}, 3000)
);
await Promise.race([
Promise.all([task1(), task2()]),
timeout
]);
}
demonstrateDeadlock();
// ============================================
// РЕШЕНИЕ 1: Упорядочение захвата ресурсов
// ============================================
setTimeout(async () => {
console.log('\n=== РЕШЕНИЕ 1: УПОРЯДОЧЕНИЕ РЕСУРСОВ ===\n');
const mutexA = new Mutex('Mutex-A');
const mutexB = new Mutex('Mutex-B');
async function task1() {
console.log('\n[TASK-1] Начало');
// ВСЕГДА захватываем в порядке A → B
await mutexA.lock();
console.log('[TASK-1] Захватил A');
await new Promise(resolve => setTimeout(resolve, 100));
await mutexB.lock();
console.log('[TASK-1] Захватил B');
console.log('[TASK-1] Работаю с обоими ресурсами...');
await new Promise(resolve => setTimeout(resolve, 50));
mutexB.unlock();
mutexA.unlock();
console.log('[TASK-1] Завершено\n');
}
async function task2() {
console.log('\n[TASK-2] Начало');
// ТАКЖЕ захватываем в порядке A → B (не B → A!)
await mutexA.lock();
console.log('[TASK-2] Захватил A');
await new Promise(resolve => setTimeout(resolve, 100));
await mutexB.lock();
console.log('[TASK-2] Захватил B');
console.log('[TASK-2] Работаю с обоими ресурсами...');
await new Promise(resolve => setTimeout(resolve, 50));
mutexB.unlock();
mutexA.unlock();
console.log('[TASK-2] Завершено\n');
}
console.log('Обе задачи захватывают ресурсы в ОДИНАКОВОМ порядке: A → B');
await Promise.all([task1(), task2()]);
console.log('✅ РЕШЕНИЕ: Никакого deadlock!\n');
}, 4000);
// ============================================
// РЕШЕНИЕ 2: Timeout при захвате
// ============================================
setTimeout(async () => {
console.log('\n=== РЕШЕНИЕ 2: TIMEOUT ===\n');
class MutexWithTimeout {
constructor(name) {
this.name = name;
this.locked = false;
this.queue = [];
}
async lock(timeoutMs = 1000) {
console.log(`[${Date.now()}] Попытка захвата ${this.name}`);
if (!this.locked) {
this.locked = true;
console.log(`[${Date.now()}] ✓ Захвачен ${this.name}`);
return true;
}
console.log(`[${Date.now()}] Ожидание ${this.name} (timeout: ${timeoutMs}ms)...`);
const lockPromise = new Promise(resolve => this.queue.push(resolve));
const timeoutPromise = new Promise(resolve =>
setTimeout(() => resolve('timeout'), timeoutMs)
);
const result = await Promise.race([lockPromise, timeoutPromise]);
if (result === 'timeout') {
// Удаляем себя из очереди
const index = this.queue.indexOf(lockPromise);
if (index > -1) this.queue.splice(index, 1);
console.log(`[${Date.now()}] ⏰ Timeout на ${this.name}`);
return false;
}
console.log(`[${Date.now()}] ✓ Захвачен ${this.name}`);
return true;
}
unlock() {
console.log(`[${Date.now()}] Освобожден ${this.name}`);
if (this.queue.length > 0) {
const resolve = this.queue.shift();
resolve('acquired');
} else {
this.locked = false;
}
}
}
const mutexA = new MutexWithTimeout('Mutex-A');
const mutexB = new MutexWithTimeout('Mutex-B');
async function taskWithRetry(id, first, second) {
console.log(`\n[TASK-${id}] Начало`);
let attempts = 0;
const maxAttempts = 5;
while (attempts < maxAttempts) {
attempts++;
console.log(`[TASK-${id}] Попытка ${attempts}`);
const gotFirst = await first.lock(500);
if (!gotFirst) {
console.log(`[TASK-${id}] Не удалось захватить первый мьютекс, повтор...`);
await new Promise(resolve => setTimeout(resolve, Math.random() * 100));
continue;
}
const gotSecond = await second.lock(500);
if (!gotSecond) {
console.log(`[TASK-${id}] Не удалось захватить второй мьютекс, откатываюсь...`);
first.unlock();
await new Promise(resolve => setTimeout(resolve, Math.random() * 100));
continue;
}
// Успешно захватили оба
console.log(`[TASK-${id}] ✅ Захватил оба мьютекса, работаю...`);
await new Promise(resolve => setTimeout(resolve, 100));
second.unlock();
first.unlock();
console.log(`[TASK-${id}] Завершено\n`);
return;
}
console.log(`[TASK-${id}] ❌ Не удалось захватить ресурсы за ${maxAttempts} попыток\n`);
}
await Promise.all([
taskWithRetry(1, mutexA, mutexB),
taskWithRetry(2, mutexB, mutexA)
]);
console.log('✅ РЕШЕНИЕ: Timeout + retry предотвращают бесконечный deadlock!\n');
}, 8000);
// ============================================
// РЕШЕНИЕ 3: Try-lock (неблокирующий захват)
// ============================================
setTimeout(async () => {
console.log('\n=== РЕШЕНИЕ 3: TRY-LOCK (неблокирующий) ===\n');
class TryLockMutex {
constructor(name) {
this.name = name;
this.locked = false;
}
tryLock() {
if (!this.locked) {
this.locked = true;
console.log(`[${Date.now()}] ✓ Захвачен ${this.name}`);
return true;
}
console.log(`[${Date.now()}] ✗ ${this.name} занят`);
return false;
}
unlock() {
console.log(`[${Date.now()}] Освобожден ${this.name}`);
this.locked = false;
}
}
const mutexA = new TryLockMutex('Mutex-A');
const mutexB = new TryLockMutex('Mutex-B');
async function taskWithTryLock(id, first, second) {
console.log(`\n[TASK-${id}] Начало`);
for (let attempt = 0; attempt < 10; attempt++) {
if (!first.tryLock()) {
await new Promise(resolve => setTimeout(resolve, 50 + Math.random() * 50));
continue;
}
if (!second.tryLock()) {
console.log(`[TASK-${id}] Не удалось захватить второй, откатываюсь...`);
first.unlock();
await new Promise(resolve => setTimeout(resolve, 50 + Math.random() * 50));
continue;
}
// Успех
console.log(`[TASK-${id}] ✅ Работаю с обоими ресурсами...`);
await new Promise(resolve => setTimeout(resolve, 100));
second.unlock();
first.unlock();
console.log(`[TASK-${id}] Завершено\n`);
return;
}
console.log(`[TASK-${id}] ❌ Не удалось\n`);
}
await Promise.all([
taskWithTryLock(1, mutexA, mutexB),
taskWithTryLock(2, mutexB, mutexA)
]);
console.log('✅ РЕШЕНИЕ: Try-lock позволяет избежать блокировки!\n');
}, 12000);