我正在启动一堆 indexeddb 操作,并希望它们能够在它们完成时增加一个计数器(并改变一些其他的东西,但是对于这个问题,假设它正在增加一个计数器)。我从IndexedDB 规范中知道它在不同的线程中运行回调(尽管有这样的措辞,但我不确定实现是否必须使用线程)。但是 AFAIK,JavaScript/HTML5 没有任何东西可以保证线程安全,所以我害怕以下情况:
/* Sequence involved in incrementing a variable "behind the scenes" */
//First callback calls i++; (it's 0 at this point)
load r0,[i] ; load memory into reg 0
//Second callback calls i++ (it's still 0 at this point)
load r1,[i] ; load memory into reg 1
//First callback's sequence continues and increments the temporary spot to 1
incr r0 ; increment reg 0
//Second callback's sequence continues and also increments the temporary spot to 1
incr r1 ; increment reg 1
//First callback sequence finishes, i === 1
stor [i],r0 ; store reg 0 back to memory
//Second callback sequence finishes, i === 1
stor [i],r1 ; store reg 1 back to memory
(或类似的规定)
那么我的选择是什么?我可以在每个调用的回调中生成网络工作者吗postMessage
并且监听器增加它吗?就像是:
increment.js(我们的 Worker 的代码)
//Our count
var count = 0;
function onmessage(event)
{
count += event.data;
}
main.js
//Our "thread-safe" worker?
var incrementer = new Worker( "increment.js" );
//Success handler (has diff thread)
req.onsuccess = function(event) {
...finish doing some work...
//Increment it
incrementer.postmessage( 1 );
};
那行得通吗?或者网络工作者的 onmessage 是否仍会出现在回调的线程中?有没有办法让它在全局线程中?