python-3.x - 延迟主线程执行,直到其他线程上不存在锁:最佳实践?
问题描述
我想在其他线程未锁定时延迟部分主线程执行。以下代码似乎按预期工作,但我想知道这是否是最好的/最好的方法(我对线程完全陌生)。
对于上下文:new_status_grid 方法在 wxpython 中创建一个新的网格,modify_simu_status 方法修改当前网格中的一些单元格值,并作为一个单独的线程执行。我想避免网格创建和网格单元写入之间的冲突。线程方法中有一个 sleep 来限制 modify_simu_status 所需的外部资源的使用。
# somewhere in the main thread
class SimuStatus(wx.Panel):
def __init__(self, parent, title):
wx.Panel.__init__(self, parent=parent)
# some code
self.thread = threading.Thread(target=self.modify_simu_status, daemon=True)
def new_status_grid(self):
# some code here
while self.lock.locked(): # wait for threads lock to be released
pass
# main thread acquires the lock, preventing modify_simu_status code to be executing
self.lock.acquire()
# destroying previous grid, if any
if self.grid_created:
for child in self.sizer.GetChildren():
widget = child.GetWindow()
if isinstance(widget, wx.grid.Grid):
widget.Destroy()
# some other code, that must not been executed if other threads are ongoing
self.lock.release()
# first time method is used, the thread is started
if not self.thread.is_alive():
self.thread.start()
def modify_simu_status(self):
"""This is the thread launched by the main thread, running ad vitam"""
while True:
self.lock.acquire()
try:
# some code that can conflict with new_status_grid code
self.lock.release()
time.sleep(refresh_time) # during this delay, the lock is released
except BaseException as e:
self.logger.error('Exception in status panel scan thread: %s ' % e)
self.lock.release()
time.sleep(refresh_time)
解决方案
推荐阅读
- observable - 我怎样才能让 RxDataSource 工作
- ubuntu - oracle java8中的格式错误的证书
- android - 更改方向时片段不使用横向布局
- amazon-web-services - 当我在我的 S3 图像上单击“在新选项卡中打开”时,它会下载图像
- sql - 上传数据时控制字符问题
- javafx - 在关闭阶段 JavaFX 之前将数据从一个控制器传递到另一个控制器
- android - 无法合并 dex。尝试了一切仍然无法正常工作
- php - 在laravel的父类别中获取子类别信息
- c - 传递多维数组的函数声明
- clojure - 在 Clojure 中将字符串转换为嵌套映射