首页 > 解决方案 > 延迟主线程执行,直到其他线程上不存在锁:最佳实践?

问题描述

我想在其他线程未锁定时延迟部分主线程执行。以下代码似乎按预期工作,但我想知道这是否是最好的/最好的方法(我对线程完全陌生)。

对于上下文: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)

标签: python-3.xmultithreading

解决方案


推荐阅读