Javascript semaphore / test-and-set / lock?

前端 未结 6 879
无人共我
无人共我 2020-12-13 23:09

Is there such a thing as an atomic test-and-set, semaphore, or lock in Javascript?

I have javascript invoking async background processes via a custom protocol (the b

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 23:49

    I had the same issue, here is how I solved it. It works fine for two concurrent processes. If you have three processes or more, it is possible that two processes start together.

    var isRunning = false;
    ...
    var id = setInterval(function(){ //loop until isRunning becomes false
                if (!isRunning){
                    isRunning = true;
                    //do something synchronous or use a promise
                    isRunning = false;
                    clearInterval(id); // stop the loop here
                }
            , 10);
    

    It is better than the while loop because it solves concurrency/async issues for reading/setting isRunning.

提交回复
热议问题