私は一連のindexeddbアクションを開始しており、それらが完了したときにカウンターをインクリメントできるようにしたい(そして他のものも変更しますが、この質問では、カウンターをインクリメントしていると仮定してください)。IndexedDB の仕様から、異なるスレッドでコールバックを実行することがわかっています (ただし、その言い回しにもかかわらず、実装でスレッドを使用する必要があるかどうかはわかりません)。しかし、私の知る限り、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
(またはそれらの線に沿った何か)
それで、私のオプションは何ですか?呼び出した各コールバックで Web ワーカーを生成postMessage
し、リスナーがそれをインクリメントすることはできますか? 何かのようなもの:
increment.js (私たちのワーカーのコード)
//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 );
};
それはうまくいくでしょうか?それとも、Web ワーカーの onmessage がコールバックのスレッドで引き続き発生するのでしょうか? グローバルスレッドにする方法はありますか?