在 LockService 文档中:https://developers.google.com/apps-script/service_lock 它指出“getPublicLock() - 获取一个锁,通过当前用户的同时执行来防止并发访问代码 的 部分”
所以查询围绕评论:“ 代码 部分”。如果我有多个使用 LockService.getPublicLock() 的代码部分,它们本质上是独立的锁吗?
例如:function test1() {
var lock = LockService.getPublicLock();
if (lock.tryLock(10000)) {
// Do some critical stuff
lock.releaseLock();
}
}
function test2() {
var lock = LockService.getPublicLock();
if (lock.tryLock(10000)) {
// Do some critical stuff
lock.releaseLock();
}
}
如果我同时执行两个脚本调用,一个用户访问 test1(),另一个用户访问 test2(),他们都会成功吗?或者正如它在这篇文章中所暗示的那样:http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html 只是脚本级别的锁吗?因此,对于这种情况,只有 test1() 或 test2() 之一会成功,但不能同时成功。
如果确实如文档所述,并且两者都会成功,那么什么表示“代码段”?是 LockService.getPublicLock() 出现的行号还是周围的函数?
最佳答案
只有一把公共(public)锁和一把私有(private)锁。
如果您希望拥有多个锁,您需要自己实现某种命名的锁服务。下面是一个使用脚本数据库功能的示例:
var validTime = 60*1000; // maximum number of milliseconds for which a lock may be held
var lockType = "Named Locks"; // just a type in the database to identify these entries
function getNamedLock( name ) {
return {
locked: false,
db : ScriptDb.getMyDb(),
key: {type: lockType, name:name },
lock: function( timeout ) {
if ( this.locked ) return true;
if ( timeout===undefined ) timeout = 10000;
var endTime = Date.now()+timeout;
while ( (this.key.time=Date.now()) < endTime ) {
this.key = this.db.save( this.key );
if ( this.db.query(
{type: lockType,
name:this.key.name,
time:this.db.between( this.key.time-validTime, this.key.time+1 ) }
).getSize()==1 )
return this.locked = true; // no other or earlier key in the last valid time, so we have it
db.remove( this.key ); // someone else has, or might be trying to get, this lock, so try again
Utilities.sleep(Math.random()*200); // sleep randomly to avoid another collision
}
return false;
},
unlock: function () {
if (this.locked) this.db.remove(this.key);
this.locked = false;
}
}
}
要使用此服务,我们将执行以下操作:
var l = getNamedLock( someObject );
if ( l.lock() ) {
// critical code, can use some fields of l for convenience, such as
// l.db - the database object
// l.key.time - the time at which the lock was acquired
// l.key.getId() - database ID of the lock, could be a convenient unique ID
} else {
// recover somehow
}
l.unlock();
笔记:
关于google-apps-script - 锁服务歧义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15091051/