如何从indexedDB回调中安全地修改全局变量?

How can I safety modify a global variable from within indexedDB callbacks?

本文关键字:修改 全局变量 安全 indexedDB 回调      更新时间:2023-09-26

我正在启动一堆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和监听器增量的每个回调中生成web工作者吗?比如:

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 worker的onmessage仍然发生在回调线程中?有没有办法使它在全局线程中?

引用的文档中唯一提到'线程'这个词是IndexedDB API方法不阻塞调用线程(这仍然不意味着方法在单独的线程中运行,尽管,它只是声明方法本质上是异步的),但没有提到回调将在不同的线程中运行。

此外,JavaScript本身是单线程的,所以你可以放心地假设回调都将在同一个('全局')线程中运行,并且将顺序调用,而不是并发调用。

所以不需要Web worker,你可以直接从回调本身增加全局变量:

req.onsuccess = function(event) {  
  count += event.data;
};