简体   繁体   English

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

[英]Pausing the “run” method in the worker thread

I have a background thread in my wxPython application to keep the GUI responsive. 我的wxPython应用程序中有一个后台线程,以保持GUI的响应速度。 There's a while(true) loop in the "run" method of my background thread but I also have other methods that I sometimes call from the GUI thread. 我的后台线程的“运行”方法中有一个while(true)循环,但我有时还会从GUI线程中调用其他方法。 Is there anyway to stop the run method while I get into another method of the background thread? 无论如何,当我进入后台线程的另一种方法时,是否要停止run方法?

Lets say you have some code like this: 假设您有一些这样的代码:

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()

The code above doesn't actually do anything, and wont even run, but I will use it to show that a function in a thread object ( MyWorkerThread.foo ) doesn't have to be called from that specific thread, it can be called from any thread. 上面的代码实际上并没有做任何事情,甚至不会跑,但我会用它来表明,在一个线程对象(一个函数MyWorkerThread.foo没有从该特定线程调用,它可以被称为从任何线程。

You may want to read more about multithreading, and maybe about semaphores to protect data from being accessed by multiple thread simultaneous. 您可能需要阅读有关多线程的更多信息,还可能需要了解有关防止多个线程同时访问数据的信号量

Do it like 做喜欢

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

     """

and somewhere else you will be able to pause thread with 在其他地方,您将可以暂停线程

stopped=True

and than use 比使用

stopped = True
alive = False

to quit thread 退出线程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM