我有一些代码看起来像这样:
def startSearching(self):
self.searchingLock.acquire()
searching = self.searching
if self.searching:
self.searchingLock.release()
self.logger.error("Already searching!")
return False
self.searching = True
self.searchingLock.release()
#some more init code, then start the thread which
#constantly checks self.searching to determine when to stop
虽然这样做看起来有点丑陋,但是需要进行大量的获取和释放。以下方式更为美观:
def startSearching(self):
with self.searchingLock:
if self.searching:
self.logger.error("Already searching!")
return False
self.searching = True
#some more init code, then start the thread which
#constantly checks self.searching to determine when to stop
但是这样会比严格必要的时间更长地保持锁定,尤其是如果 self.logger.error
需要一段时间(例如写入磁盘),那么情况就更加如此了。有没有折衷方案可以尽可能地减少锁定时间,同时又能让代码更加优雅?