【问题标题】:is it possible to mutex lock a variable in javascript like you would in c++?是否可以像在 c++ 中那样在 javascript 中互斥锁变量?
【发布时间】:2022-11-20 04:56:14
【问题描述】:

对于某些情况 - 我已经搜索了很多问题但没有运气。首先,我想知道“箭头函数”是否是线程化的,例如

query(query, (err, res) => {}); 

如果我将该查询放入运行 4 次的 for 循环中,是否会同时查询数据库?所以大括号内的逻辑会一起运行吗?-因为如果它们不一致,就无法解释我的逻辑行为。因为它偶尔会返回正确数量的结果,有时不会 - 该行为与具有未处理的读/写权限的线程函数相同。

其次,如果箭头函数是线程化的,我如何锁定变量和数组,以便一次只有一个人可以访问它

我试过在没有 sql 查询箭头函数的情况下运行 for 循环,当然它会返回正常的“i”值。但在查询中它们是不可预测的。

 let sendBack = new Array(modIdArray.length); // this is what im using to send back data, it may increase in size. 
  let x = 0 // i'd like this to be mutex protected aswell as sendBack array
  for(let i = 0; i < modIdArray.length; i++){
    
    console.log( i, " : i here")
    let query = `SELECT * FROM attendence.lectures WHERE moduleID = '${modIdArray[i]}'`;
   
    sql.query(query, (err, res) => {
      if (err) {
        console.log("error: ", err);
        result(null, err);
        return;
      }; // use to increment sendBack array
      console.log( i, " : i here")
      
      if (res.length > 1){ // if the query returns two "results" in this loop then it'll put them into one element of "sendBack" each. 
        console.log(res.length, "  : res.legnth in more than One")
        for(let j =0; j < res.length; j ++){
          sendBack[x] = res[j]
          console.log(sendBack[x],x," : re")
          x++;
        }


        
      }else{
        console.log(res.length, "  : res.legnth")
        sendBack[x] = res[0]
        console.log(sendBack[x],x, " : rrr")
        x++;
      }
      console.log(x , "   : x here")
      //receive[i]= res
      
      if(i == (modIdArray.length -1) ){ // on the final iteration of the loop/ send forth the results 
        //console.log(sendBack);
        result(null, sendBack);
      }


    });
  }

这是逻辑---问题是每个查询可能会给我一个“结果”或一个查询的多个结果。所以我想将它们全部放入一个数组中,这样每个结果都是它自己的一个元素 - 但是对于上面的代码,这只是偶尔发生,而其他时候显示的结果比应该的要少

【问题讨论】:

  • JavaScript 不是多线程的。
  • 如果我将该查询放入运行 4 次的 for 循环中,是否会同时查询数据库?" - 这取决于 query 在做什么。而不是箭头函数。请注意 query 可能是异步的,因此您的循环可能确实会在稍后调用所有回调之前立即触发数据库查询;但那是不是多线程。
  • 如果您需要循环方面的帮助,请edit您的帖子以添加实际代码(包括循环、query 的定义以及回调中的代码)。不过,您的问题很可能与how to deal with closures in a loop 重复。
  • 添加了我的逻辑——“sendBack”中的所有内容都按原样从端点发送出去。我还控制台记录了每个处理“res”(查询结果承诺)大小的 if 语句。他们都返回正确的结果和正确的数量。但是 sendBack 总是填充随机数量的结果

标签: javascript multithreading mutex


【解决方案1】:

你所做的基本上是

function next(...a) {
  console.log(...a)
}

let j = 0;
for (let i = 0; i < 5; i++) {
  setTimeout(() => next(i, j+=i), Math.random() * 1000)
}

你只是不小心处理它。

要以有序的方式处理异步结果,您应该使用 Promises,请参阅有关如何使用它们的库文档

【讨论】:

  • 我已经添加了我的逻辑 - 看你什么时候可以
猜你喜欢
  • 2010-09-12
  • 2011-09-06
  • 2014-12-30
  • 2021-04-16
  • 2015-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多