Skip to content

Commit

Permalink
자바스크립트 : Mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
Henry-Hong committed Nov 10, 2024
1 parent 3df81b1 commit e175a4d
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/**/tempCodeRunnerFile.js
/**/tempCodeRunnerFile.js
/**/node_modules
63 changes: 63 additions & 0 deletions 자바스크립트/concurrent/my-mutex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* Promise.all을 사용하는 경우, 한번에 모든 Promise를 처리하므로, mutex를 걸어준다.
* 혹은 forEach, map 대신 reduce를 사용하거나, for문 사용해도 가능하다.
*/

class Mutex {
constructor() {
this._isLocked = false;
}

lock() {
this._isLocked = true;
}

unlock() {
this._isLocked = false;
}

release() {
this.unlock();
}

async acquire(count = 0) {
if (count >= 10) throw new Error("Mutex lock count exceeded");

const isLocked = this._isLocked;
if (!isLocked) {
this.lock();
return Promise.resolve();
} else {
return new Promise((resolve) => {
setTimeout(() => {
this.acquire(count + 1).then(resolve);
}, 100);
});
}
}
}

let sum = 0;
const mutex = new Mutex();

const wait = () =>
new Promise((resolve) => setTimeout(resolve, Math.random() * 50));

async function add(order) {
await mutex.acquire();
console.log(`[${order}] start`);

await wait(); // async logic
sum += 1;

console.log(`[${order}] end`);
mutex.release();
}

async function main() {
console.log("start");
await Promise.all([add(1), add(2), add(3)]);
console.log("end");
}

main();
17 changes: 17 additions & 0 deletions 자바스크립트/concurrent/recursive-async.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
async function recursiveAsync(count = 0) {
console.log("count is", count);
return new Promise((resolve) =>
setTimeout(async () => {
await recursiveAsync(count + 1);
resolve();
}, 500)
);
}

async function main() {
console.log("start");
await recursiveAsync();
console.log("end");
}

main();

0 comments on commit e175a4d

Please sign in to comment.