2012-07-24 120 views
0

“运行”的方法我有一个后台线程在我的wxPython应用程序,以保证GUI作出响应。 有一段时间(true)循环在我的后台线程的“运行”的方法,但我也有其他的方法,我有时从GUI线程中调用。无论如何,当我进入后台线程的另一种方法时停止运行方法?暂停在工作线程

+0

为什么?如果您从UI函数调用方法,它们将在UI线程的上下文中运行,但仍可以访问工作线程内的变量和内容。您可能不得不用这些变量保护这些变量。但是信号量。 – 2012-07-24 12:38:42

+0

对不起,我对Python很新,所以我不确定你的意思。我想从GUI方法中调用工作线程方法(它已经在运行它的运行方法的while循环中)。 – Milad 2012-07-24 12:41:35

回答

0

做到像

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

    """ 

和别的地方,你将能够暂停线程与

stopped=True 

,比使用

stopped = True 
alive = False 

退出线程

1

让说你有一些c颂这样的:

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保护由多个线程同时被访问的数据。

+0

谢谢。所以当我从SomeRandomButton调用foo时,它会在MyWorkerThread线程还是按钮所属的线程上运行? – Milad 2012-07-24 13:03:14

+0

@Milad它将在线程中运行按钮所属,这就是为什么你可能需要使用信号来保护数据。 – 2012-07-24 13:16:13

+0

我明白了!那么这是否意味着我必须为我的GUI中的每个操作定义一个单独的线程以保持其响应? – Milad 2012-07-24 13:44:20