gpt4 book ai didi

python:处理变量锁定的优雅方法?

转载 作者:太空狗 更新时间:2023-10-29 21:38:23 25 4
gpt4 key购买 nike

我的代码看起来像这样:

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 需要一段时间(就像它写入磁盘一样,它会这样做)。在尽可能少地持有锁和拥有更漂亮的代码之间是否有中间立场?

最佳答案

也许你需要像这样分离这个逻辑:

def initSearch(self):
with self.searchingLock:
if self.searching : raise SearchingError('AlreadySearching')
self.searching = True
def startSearching(self):
try: self.initSearch()
except SearchingError as error :
self.logger.error(error.message)
return False
#some more init code, then start the thread which
#constantly checks self.searching to determine when to stop

另外,您告诉您的 searchingLock 自动释放它的原因。

关于python:处理变量锁定的优雅方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3462566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com