暂停工作线程中的“run”方法

时间:2012-07-24 12:33:25

标签: python multithreading wxpython python-multithreading

我的wxPython应用程序中有一个后台线程来保持GUI响应。 在我的后台线程的“run”方法中有一段时间(真实)循环,但我还有其他方法,我有时会从GUI线程调用。无论如何在我进入后台线程的另一个方法时停止run方法?

2 个答案:

答案 0 :(得分: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来保护数据不被多线程同时访问。

答案 1 :(得分:0)

喜欢

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

     """

以及其他地方你可以用

暂停线程
stopped=True

而不是使用

stopped = True
alive = False

退出线程

相关问题