Skip to content

Commit

Permalink
feat: 🎸 add timeout to spin lock
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Jun 20, 2023
1 parent 969afa6 commit 1e2fc72
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/fsa-to-node/worker/SyncMessenger.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
export type AsyncCallback = (request: Uint8Array) => Promise<Uint8Array>;

const microSleepSync = () => {
// Math.random();
};

const sleepUntilSync = (condition: () => boolean) => {
while (!condition()) microSleepSync();
/**
* @param condition Condition to wait for, when true, the function returns.
* @param ms Maximum time to wait in milliseconds.
*/
const sleepUntil = (condition: () => boolean, ms: number = 100) => {
const start = Date.now();
while (!condition()) {
const now = Date.now();
if (now - start > ms) throw new Error('Timeout');
}
};

/**
Expand Down Expand Up @@ -42,7 +46,7 @@ export class SyncMessenger {
int32[2] = requestLength;
this.uint8.set(data, headerSize);
Atomics.notify(int32, 0);
sleepUntilSync(() => int32[1] === 1);
sleepUntil(() => int32[1] === 1);
const responseLength = int32[2];
const response = this.uint8.slice(headerSize, headerSize + responseLength);
return response;
Expand Down

0 comments on commit 1e2fc72

Please sign in to comment.