我正在我的 Chrome 浏览器中测试 Javascript Atomics。
对于一个非常简单的测试,我想在 Atomics.wait
上使用
Atomics.notify
和
SharedArray
来定义具有一些简单规则的互斥锁:
我在缓冲区中使用位置 0 来存储互斥量。如果互斥锁包含 1,则轮到编写者了。如果它包含 0,则轮到读者了。
我用
Atomics.wait
睡觉,Atomics.store
改变值(我什至需要原子写吗?毕竟我应该在互斥体中)和 Atomics.notify
只通知一个读者/作家。读取器和写入器函数由随机 setTimeout 重新排队(当读取器完成时,它会排队另一个读取)
function randomlyRead() {
// Reader
Atomics.wait(view, 0, 1); // Wait for int32 at 0 to be different than 1
console.log("Lock granted for reader, int32 at 0 should be 0 =>", view[0]);
//... read
Atomics.store(view, 0, 1); // set it to 1, ready for writing
console.log("Reader unlocking writer");
// Unlock
Atomics.notify(view, 0, 1); // Notify just 1 listener at location 0
setTimeout(randomlyWrite, Math.floor(Math.random() * 15000));
}
// Writer
function randomlyWrite() {
Atomics.wait(view, 0, 0); // Wait for int32 at 0 to be different than 0
console.log("Lock granted for writer, int32 at 0 should be 1 =>", view[0]);
//... write
Atomics.store(view, 0, 0); // set it to 0, ready for reading
console.log("Writer unlocking reader");
// Unlock
Atomics.notify(view, 0, 1); // Notify just 1 listener at location 0
setTimeout(randomlyWrite, Math.floor(Math.random() * 15000));
}
我期望的是作者和一位读者一次轮流阅读和写作。实际上,它们似乎很快就会失去同步,我开始看到连续读取,三个读取器连续读取,并且在进入互斥量时值不是预期的值(不过这可能是异步 console.log 的本质吗?如果是的,我该如何调试 Atomics?):
Lock granted for reader, int32 at 0 should be 0 -> 0
reader.ts?type=classic&worker_file:28 Reader unlocking writer
writer.ts?type=classic&worker_file:22 Lock granted for writer, int32 at 0 should be 1 -> 1
writer.ts?type=classic&worker_file:29 Writer unlocking reader
reader.ts?type=classic&worker_file:22 Lock granted for reader, int32 at 0 should be 0 -> 0
reader.ts?type=classic&worker_file:28 Reader unlocking writer
writer.ts?type=classic&worker_file:22 Lock granted for writer, int32 at 0 should be 1 -> 1
writer.ts?type=classic&worker_file:29 Writer unlocking reader
reader.ts?type=classic&worker_file:22 Lock granted for reader, int32 at 0 should be 0 -> 0
reader.ts?type=classic&worker_file:28 Reader unlocking writer
reader.ts?type=classic&worker_file:22 Lock granted for reader, int32 at 0 should be 0 -> 1
reader.ts?type=classic&worker_file:28 Reader unlocking writer
reader.ts?type=classic&worker_file:22 Lock granted for reader, int32 at 0 should be 0 -> 1
reader.ts?type=classic&worker_file:28 Reader unlocking writer