我有一个使用 HTML LocalStorage 的网页。同时打开此页面的多个选项卡/窗口是很常见的。由于这些都使用相同的 LocalStorage 并且 LocalStorage 不提供事务或类似功能,因此我想实现某种形式的互斥,以防止不同的选项卡/窗口以不受控制的方式覆盖彼此的数据。
我尝试只移植我对 Burns/Lynch 互斥算法的测试 https://stackoverflow.com/questions/33270575/implementing-mutual-exclusion-algorithm-by-burns-and-lynch-in-java-could-there通过简单地存储到浏览器boolean[] F
在本地存储中。
在 FireFox 中一切正常,但 Chrome 平均允许大约 1.3 个进程(大多数是 1 个,有时是 2 个,很少甚至 3 个或更多)同时进入关键部分,而 Internet Explorer 平均允许 2 个进程(大多数是1、2 或 3,有时甚至更多)。
自从算法已被证明是正确的 http://groups.csail.mit.edu/tds/papers/Lynch/allertonconf.pdf我的实现非常简单,我已经测试了它,否则,我能想到为什么会发生这种情况的唯一原因是,在 Chrome 和 IE 中,当我写入 LocalStorage 时存在延迟一个选项卡/窗口以及新值何时在所有其他选项卡/窗口中可见。
这可能吗?如果是这样,是否有任何文件或对这些延误有任何保证?或者,更好的是,是否有某种“commit”或“flush()”调用可以用来强制更改立即传播?
UPDATE:
我整理了一点jsfiddle http://jsfiddle.net/nLogLjLy/8/测试往返时间:
// Get ID
var myID;
id = window.localStorage.getItem("id");
if (id==1) { myID = 1; window.localStorage.setItem("id", 0); }
else { myID = 0; window.localStorage.setItem("id", 1); }
// Initialize statistics variables
var lastrun = (new Date()).getTime();
var totaldelay = 0;
var count = 0;
var checks = 0;
document.documentElement.innerHTML = "ID: "+myID;
// Method that checks the round-trip time
function check() {
window.setTimeout(check, 1); // Keep running
value = window.localStorage.getItem("state");
checks++;
if (value==myID) return;
window.localStorage.setItem("state", myID);
now = new Date().getTime();
totaldelay += now - lastrun;
count++;
lastrun = now;
document.documentElement.innerHTML = "ID: "+myID+"<br/>"+
"Number of checks: "+checks+"<br/>"+
"Number of round-trips: "+count+"<br/>"+
"Checks per round-trip: "+checks/count+"<br/>"+
"Average round-trip time:"+totaldelay/count;
}
// Go!
window.setTimeout(check, 1000);
如果我在两个不同的窗口中运行这个小提琴,我会在打开的第二个窗口中得到以下数字:
Browser | Checks per round-trip | Average round-trip time
------------------+-----------------------+-------------------------
Firefox 24.3.0 | 1.00 | 6.1 ms
Chrome 46.0.2490 | 1.06 | 5.5 ms
IE 10 | 17.10 | 60.2 ms