`postMessage` 或屈服于事件循环或类似的同步共享内存吗?

Does `postMessage` or yielding to the event loop or similar sync shared memory?

我在 the JavaScript spec, the proposed DOM spec extensions related to SharedArrayBuffer, or the current WHAT-WG HTML spec 中没有看到任何暗示当一个线程向另一个线程发布消息而另一个线程处理该消息时共享内存将 synchronized/updated 跨线程。 (之后,一个已经将共享内存发送给另一个。)但是,我也无法通过实验验证它不会发生(在我的测试中,我没有看到过时的值)。是否有这样的保证我失踪了,如果有,它在哪里保证?例如,它是否记录了 postMessage 而我错过了它,或者是否有关于返回事件循环/作业队列的东西来保证它(因为处理来自另一个线程的消息涉及这样做),等等.?或者,是否绝对 保证(并且该信息在某处的规范中)?

不要推测或制造 "reasonable guess." 我正在寻找可靠的信息:来自规范来源的引文,一个可复制的实验表明它不能保证(尽管我想这是否只是一个实现错误的问题),诸如此类。


以下是我的测试的源代码,但尚未能够捕获未同步的内存。要 运行 它,您需要使用当前支持 SharedArrayBuffer 的浏览器,我认为目前这意味着 Chrome v67 或更高版本(Firefox、Edge 和 Safari 都有支持,但在 2018 年 1 月响应 Spectre 和 Meltdown 将其禁用;Chrome 也这样做了,但在 v67 [2018 年 7 月] 中在启用了站点隔离功能的平台上重新启用了它。

sync-test-postMessage.html:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Sync Test postMessage</title>
</head>
<body>
<script src="sync-test-postMessage-main.js"></script>
</body>
</html>

sync-test-postMessage-main.js:

const array = new Uint32Array(new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT));
const worker = new Worker("./sync-test-postMessage-worker.js");
let counter = 0;
const limit = 1000000;
const report = Math.floor(limit / 10);
let mismatches = 0;
const now = performance.now();
const log = msg => {
    console.log(`${msg} - ${mismatches} mismatch(es) - ${performance.now() - now}ms`);
};
worker.addEventListener("message", e => {
    if (e.data && e.data.type === "ping") {
        ++counter;
        const value = array[0];
        if (counter !== value) {
            ++mismatches;
            console.log(`Out of sync! ${counter} !== ${value}`);
        }
        if (counter % report === 0) {
            log(`${counter} of ${limit}`);
        }
        if (counter < limit) {
            worker.postMessage({type: "pong"});
        } else {
            console.log("done");
        }
    }
});
worker.postMessage({type: "init", array});
console.log(`running to ${limit}`);

sync-test-postMessage-worker.js:

let array;
this.addEventListener("message", e => {
    if (e.data) {
        switch (e.data.type) {
            case "init":
                array = e.data.array;
                // fall through to "pong"
            case "pong":
                ++array[0];
                this.postMessage({type: "ping"});
                break;
        }
    }
});

使用该代码,如果内存未同步,我希望主线程在某个时候看到共享数组中的陈旧值。但完全有可能(在我看来)此代码仅 碰巧 起作用,因为消息传递涉及相对较大的时间尺度...

TL;DR: 是的。


the thread on es-discuss中,共享内存提案的作者Lars Hansen写道:

In a browser, postMessage send and receive was always intended to create a synchronization edge in the same way a write-read pair is. http://tc39.github.io/ecmascript_sharedmem/shmem.html#WebBrowserEmbedding

Not sure where this prose ended up when the spec was transfered to the es262 document.

我跟进了:

Thanks!

Looks like it's at least partially here: https://tc39.github.io/ecma262/#sec-host-synchronizes-with

So, a question (well, two questions) just for those of us not deeply versed in the terminology of the Memory Model section. Given:

  1. Thread A sends a 1k shared block to Thread B via postMessage
  2. Thread B writes to various locations in that block directly (not via Atomics.store)
  3. Thread B does a postMessage to Thread A (without referencing the block in the postMessage)
  4. Thread A receives the message and reads data from the block (not via Atomics.load)

...am I correct that in Step 4 it's guaranteed that thread A will reliably see the writes to that block by Thread B from Step 2, because the postMessage was a "synchronization edge" ensuring (amongst other things) that CPU L1d caches are up-to-date, etc.?

Similarly, if (!) I'm reading it correctly, in your Mandlebrot example, you have an Atomics.wait on a single location in a shared block, and when the thread wakes up it seems to assume other data in the block (not in the wait range) can reliably be read directly. That's also a "synchronization edge"?

他回复了:

...ensuring (amongst other things) that CPU L1d caches are up-to-date, etc.?

是的,这就是该语言的意图。对内存的写入应该发生在 postMessage 之前,而接收消息应该发生在读取之前。

... That's also a "synchronization edge"?

是的,同样的论点。写入发生在唤醒之前,等待的唤醒发生在读取之前。

所有这些都是有意为之,以便允许使用廉价的非同步写入和读取来写入和读取数据,然后进行(相对昂贵的)同步以确保适当的可观察性。