Javascript 处理并发性

Javascript 处理并发性,javascript,Javascript,下面的代码显然存在并发性问题 var a, b, c, d; function f1() { var randomValue = Math.random(); a = b = randomValue; setTimeout(function() { expect(a == b && b == randomValue); }, Math.round(Math.random() * 1000)); } function f2() {

下面的代码显然存在并发性问题

var a, b, c, d;

function f1() {
    var randomValue = Math.random();
    a = b = randomValue;
    setTimeout(function() {
        expect(a == b && b == randomValue);
    }, Math.round(Math.random() * 1000));
}
function f2() {
    var randomValue = Math.random();
    b = c = randomValue;
    setTimeout(function() {
        expect(b == c && c == randomValue);
    }, Math.round(Math.random() * 1000));
}
function f3() {
    var randomValue = Math.random();
    c = d = randomValue;
    setTimeout(function() {
        expect(c == d && d == randomValue);
    }, Math.round(Math.random() * 1000));
}
function f4() {
    var randomValue = Math.random();
    d = a = randomValue;
    setTimeout(function() {
        expect(d == a && a == randomValue);
    }, Math.round(Math.random() * 1000));
}

f1(); f2(); f2(); f4();

这可以通过将所有函数夹在信号量的等待和信号之间来解决。然而,这种方法并不是最好和最有效的,因为f1和f3可以同时运行而不会遇到任何问题,f2和f4也可以。而且我更喜欢利用javascripts事件循环,而不是使用信号量。解决这个问题的最好办法是什么?如何将解决方案扩展到具有更多变量的更多函数?

你是说f2和f4对吗?@WouterHuysentruit是的。谢谢。您是否应该使用某种超时队列来保持同步?此外,您还可以始终锁定部分方法