From 2f115c99d42de6f9b58153aece5fdb5585e2478d Mon Sep 17 00:00:00 2001 From: blinry Date: Thu, 7 Sep 2023 18:00:24 +0200 Subject: [PATCH] Add mutex to web-shell --- web/web-shell/script.js | 74 ++++++++++++++++++++++++++++++----------- 1 file changed, 54 insertions(+), 20 deletions(-) diff --git a/web/web-shell/script.js b/web/web-shell/script.js index 53093d3..c9a67d5 100644 --- a/web/web-shell/script.js +++ b/web/web-shell/script.js @@ -1,4 +1,32 @@ -//import {Mutex} from "./mutex.js" +class Mutex { + constructor() { + this._queue = [] // Queue of pending tasks + this._locked = false // Mutex state + } + + lock() { + if (this._locked) { + // If locked, return a promise that resolves when the mutex is unlocked + return new Promise((resolve) => this._queue.push(resolve)) + } else { + // If not locked, set it to locked and return a resolved promise + this._locked = true + return Promise.resolve() + } + } + + unlock() { + if (this._queue.length > 0) { + // If there are tasks waiting in the queue, pop the first task and resolve its promise + const nextTask = this._queue.shift() + nextTask() + } else { + // If no tasks in the queue, just unlock the mutex + this._locked = false + } + } +} +const mutex = new Mutex() var emulator @@ -16,29 +44,35 @@ window["testy"] = testy // Run a command via the serial port (/dev/ttyS0) and return the output. function run(cmd) { - emulator.serial0_send(cmd + "\n") - return new Promise((resolve, reject) => { - var output = "" - var listener = (char) => { - if (char !== "\r") { - output += char - } + mutex.lock().then(() => { + emulator.serial0_send(cmd + "\n") - if (output.endsWith("# ")) { - emulator.remove_listener("serial0-output-char", listener) - let outputWithoutPrompt = output.slice(0, -4) - let outputWithoutFirstLine = outputWithoutPrompt.slice( - outputWithoutPrompt.indexOf("\n") + 1 - ) - if (outputWithoutFirstLine.endsWith("\n")) { - outputWithoutFirstLine = outputWithoutFirstLine.slice(0, -1) + var output = "" + var listener = (char) => { + if (char !== "\r") { + output += char + } + + if (output.endsWith("# ")) { + emulator.remove_listener("serial0-output-char", listener) + let outputWithoutPrompt = output.slice(0, -4) + let outputWithoutFirstLine = outputWithoutPrompt.slice( + outputWithoutPrompt.indexOf("\n") + 1 + ) + if (outputWithoutFirstLine.endsWith("\n")) { + outputWithoutFirstLine = outputWithoutFirstLine.slice( + 0, + -1 + ) + } + emulator.remove_listener("serial0-output-char", listener) + mutex.unlock() + resolve(outputWithoutFirstLine) } - emulator.remove_listener("serial0-output-char", listener) - resolve(outputWithoutFirstLine) } - } - emulator.add_listener("serial0-output-char", listener) + emulator.add_listener("serial0-output-char", listener) + }) }) } window["run"] = run