javascript - 我应该担心这里的比赛条件吗?
问题描述
我在javascript中有一个类,具有以下结构:
class TableManager {
/** an array containing Table objects **/
protected Tables = [];
protected getTable(tableId) {
// iterates over this.Tables, and searches for a table with a specific id: if found, it returns the table object, otherwise it returns null
}
protected async createTable(tableId) {
const Table = await fetchTable(tableId); /** performs an asynchronous operation, that creates a Table object by performing a select operation on the database **/
this.Tables.push(Table);
return Table;
}
protected async joinTable(user, tableId) {
const Table = this.getTable(tableId) ?? await this.createTable(tableId);
Table.addUser(user);
}
}
这个类背后的想法是,它将通过套接字接收命令。例如,它可能会收到joinTable
命令,在这种情况下,它应该首先检查正在连接的表是否已经存在于内存中:如果存在,则将用户添加到该表中,否则,它将创建表,将其存储在内存中,并将用户添加到表中。
我有点担心,如果joinTable()
在短时间内进行两次调用,这可能会导致竞争条件,在这种情况下,表将被创建两次,并作为两个单独的表实例存储在内存中。我对此感到害怕是对的吗?如果是,是否会在将表添加到createTable
函数中的数组之前检查表是否存在,解决这个竞争条件?
解决方案
你的担心是对的。这个想法是事务,并确保在给定时间只有一个事务在运行。在 Nodejs 中,您可以使用 Mutex 来实现它。阅读更多:https ://www.nodejsdesignpatterns.com/blog/node-js-race-conditions/ 。
推荐阅读
- plsql - 嵌套 case 中的 case 语句
- visual-studio - Azure DevOps - Visual Studio - 本地调试
- swift - 从泛型类继承时无法调用协议上的可选函数
- python - 在 PythonScriptStep 中记录指标
- linux - db2prereqcheck 实用程序无法确定 Linux 分发级别
- arrays - 从锯齿状数组中提取子数组并用作一维数组
- javascript - 如何在 javascript 中从此对象获取宽度和高度值
- reactjs - 我无法从 VS 代码编译代码以在浏览器上运行?
- postgresql - 禁用位图扫描时 Postgres 返回不同的结果
- jquery - 目标特定按钮 - Jquery