【问题标题】:Pausing the "run" method in the worker thread暂停工作线程中的“运行”方法
【发布时间】:2012-07-24 12:33:24
【问题描述】:

我的 wxPython 应用程序中有一个后台线程来保持 GUI 响应。 我的后台线程的“运行”方法中有一个 while(true) 循环,但我也有其他方法,有时我会从 GUI 线程调用。当我进入后台线程的另一种方法时,是否有停止运行方法的方法?

【问题讨论】:

  • 为什么?如果您从 UI 函数调用方法,它们将在 UI 线程的上下文中运行,但仍可以访问工作线程内的变量和内容。您可能必须使用例如保护这些变量。信号量。
  • 对不起,我对 Python 很陌生,所以我不确定你的意思。我想从 GUI 方法调用工作线程方法(在运行它的 run 方法时已经在一个 while 循环中)。

标签: python multithreading wxpython python-multithreading


【解决方案1】:

假设你有一些这样的代码:

import threading
import time

class MyWorkerThread(threading.Thread):
    def run():
        while True:
            # Do some important stuff here
            foo()
            time.sleep(0.5)

    def foo():
        # Do something important here too
        pass

class SomeRandomButton:
    def __init__(worker_thread):
        self.worker_thread = worker_thread

    # Function called when button is clicked
    def on_button_clicked():
        self.worker_thread.foo();

my_worker_thread = MyWorkerThread()
my_button = SomeRandomButton(my_worker_thread)

# Start thread
my_worker_thread.run()

# Initialize the GUI system (creating controls etc.)

# Start GUI system
GUISystem.run()

上面的代码实际上并没有做任何事情,甚至不会运行,但我会用它来说明线程对象 (MyWorkerThread.foo) 中的函数不必须从该特定线程调用,它可以从任何线程调用。

您可能想了解更多关于多线程的信息,也许还想了解semaphores 以保护数据不被多个线程同时访问。

【讨论】:

  • 谢谢。那么当我从 SomeRandomButton 调用 foo 时,它会运行在 MyWorkerThread 线程还是按钮所属的线程上?
  • @Milad 它将在按钮所属的线程中运行,这就是为什么您可能必须使用信号量来保护数据。
  • 我明白了!那么这是否意味着我必须为我的 GUI 中的每个操作定义一个单独的线程以保持响应?
  • @Milad 不,GUI 系统会处理这个问题。只有当您有长时间运行的事件时,例如下载文件或一些繁重的数字运算,您才需要为此创建一个新线程。
【解决方案2】:

这样做

while(alive):
  while(not stopped):
     """
        thread body

     """

你可以在其他地方暂停线程

stopped=True

比使用

stopped = True
alive = False

退出线程

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 2018-07-16
    相关资源
    最近更新 更多