对mapLimit返回的变量进行独占访问

问题描述 投票:0回答:1

我是在nodejs编程而不是编程(C / C ++ / Python / Shaders)的新手,我有一个关于对全局变量进行独占访问的问题。 async.mapLimit返回其回调

var myGlobalCounter = 0;

function executeDownload(item, callback){

  exec('./ascriptthatdownload.sh ' + item, function (error, stdout, stderr) {
    // Here do I have exclusive access to myGlobalCounter
    // so that I could do this or update lets say a UI component?
    myGlobalCounter++
    console.log('Downloads ready:', myGlobalCounter);
  });   
}

function downloadSomeFiles() {
  var listOfFiles = [];
  // create download links
  async.mapLimit(listOfFiles, 4, executeDownload, function(err, results){

  });
}

我可以让这个工作,但我不知道这是否足够安全?其他建议也表示赞赏。在C / C ++中,我会使用互斥锁来防止同时访问myGlobalCounter。

编辑:我希望每次下载准备就能安全地将myGlobalCounter计数为1,然后在console.log中传递给另一个组件

node.js async.js
1个回答
0
投票

荣誉在他的评论中转到@CertainPerformance解释(我不能接受作为答案)

是的,Javascript是单线程的 - 在任何其他回调可以运行之前,同步代码块将运行到最后,查找事件循环。您几乎不必担心JS中的共享可变状态

© www.soinside.com 2019 - 2024. All rights reserved.