首页 > 解决方案 > 我应该担心这里的比赛条件吗?

问题描述

我在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函数中的数组之前检查表是否存在,解决这个竞争条件?

标签: javascriptrace-condition

解决方案


你的担心是对的。这个想法是事务,并确保在给定时间只有一个事务在运行。在 Nodejs 中,您可以使用 Mutex 来实现它。阅读更多:https ://www.nodejsdesignpatterns.com/blog/node-js-race-conditions/ 。


推荐阅读