javascript关键部分或信号量问题

function myobj(){ var gup=this; this.lastindex=-1; this.criticalSectionInTimer=0; this.updateTimer; this.start = function(l){ if((typeof this.updateTimer)=="number"){ clearInterval ( this.updateTimer ); } this.updateTimer=setInterval(function() {gup.getMessages();} , 30); } this.stop= function(){ if((typeof this.updateTimer)=="number"){ clearInterval ( this.updateTimer ); } } this.addUpdate(i){ //some code } this.rrrrnr=0; this.getMessages = function (){ if(this.criticalSection==0){ this.criticalSection=1; this.rrrrnr++; console.log("in critical section"+this.rrrrnr); var url="getmessages.php?lastindex="+this.lastindex; $.getJSON(url, function(data){ gup.lastindex=data.lastindex; $.each(data.updates, function(i,item){ gup.addUpdate(item); }); } ); console.log("out critical section"+this.rrrrnr); this.criticalSection=0; } } } var m= new myobj(); myobj.start(); 

我有上面的代码。 我有一个主循环,它以给定的时间间隔进行更新。 问题是我已经意识到它正在进入“关键部分”,我已经通过变量this.criticalSection分隔。

从firebug我得到消息“在临界区”+索引和“out critical section”+索引按正确的顺序,但ajax请求仍在处理中。 但我得到相同索引的请求,我真的不知道在哪里寻找问题。

在javascript中是否有信号量或关键部分的buildinfunction?

没有信号量或关键部分,因为JavaScript是单线程的。 你做的ajax调用是异步的,所以它启动了请求,然后愉快地继续前进并离开你的关键部分。 正如其他人所提到的,一个简单的解决方案是使请求同步,但这违背了ajax的目的。

查看您的代码,您似乎正在尝试定期更新。 如果是这种情况,为什么不在ajax请求的回调中安排下一次更新?

 this.getMessages = function (){ var url="getmessages.php?lastindex="+this.lastindex; $.getJSON(url, function(data){ gup.lastindex=data.lastindex; $.each(data.updates, function(i,item){ gup.addUpdate(item); }); gup.updateTimer=setTimeout(gup.getMessages, 30); } ); } 

这将消除对信号量的需求,并且更符合JavaScript的事件驱动特性。 缺点是更新不是按照确切的时间间隔完成的。 此外,30毫秒似乎是一个非常短的间隔。

jQuery默认发送AJAX Async。 做了getJSON的尝试尝试:

 $.ajax({ dataType: 'json', url: url, type: 'GET', async: false, success: function(data){ gup.lastindex=data.lastindex; $.each(data.updates, function(i,item){ gup.addUpdate(item); }); }); 

问题很简单。

您正在使用AJAX,根据定义,它是异步的。 这意味着,您执行$ .getJSON,并且js将继续并在处理请求时退出临界区。 因此,可以在第一个请求完成之前执行多次getMessages调用。

看来你打算这样的getJSON调用不是异步的,并且在关键部分被阻塞直到它结束。 为此,您必须将async属性设置为false,其行如下:

 $.ajax({ dataType: 'json', url: "getmessages.php?lastindex="+this.lastindex, type: 'GET', async: false, success: function(data){ gup.lastindex=data.lastindex; $.each(data.updates, function(i,item){ gup.addUpdate(item); }); });