jim*_*mbo 18 python multithreading wxpython
我有一个很长的进程,我计划在一个线程中运行,否则它会冻结我的wxpython应用程序中的ui.
我正在使用
threading.Thread(target = myLongProcess).start()
Run Code Online (Sandbox Code Playgroud)
启动线程并且它可以工作,但我不知道如何暂停和恢复线程.我在python文档中查找了上述方法,但无法找到它们.
谁能建议我怎么做?
谢谢.
小智 13
我自己也有同样的问题,直到找到答案.
我也进行了一些速度测试,在缓慢的2处理器Linux机箱上设置标志和采取行动的时间是快速的0.00002秒.
作者Rich O'Regan
import threading
import time
# This function gets called by our thread.. so it basically becomes the thread innit..
def wait_for_event(e):
while True:
print '\tTHREAD: This is the thread speaking, we are Waiting for event to start..'
event_is_set = e.wait()
print '\tTHREAD: WHOOOOOO HOOOO WE GOT A SIGNAL : %s', event_is_set
e.clear()
# Main code..
e = threading.Event()
t = threading.Thread(name='your_mum',
target=wait_for_event,
args=(e,))
t.start()
while True:
print 'MAIN LOOP: still in the main loop..'
time.sleep(4)
print 'MAIN LOOP: I just set the flag..'
e.set()
print 'MAIN LOOP: now Im gonna do some processing n shi-t'
time.sleep(4)
print 'MAIN LOOP: .. some more procesing im doing yeahhhh'
time.sleep(4)
print 'MAIN LOOP: ok ready, soon we will repeat the loop..'
time.sleep(2)
Run Code Online (Sandbox Code Playgroud)
没有其他线程强制暂停线程的方法(除了其他线程杀死该线程之外) - 目标线程必须通过偶尔检查适当的"标志"(threading.Condition
可能适合于暂停/取消暂停)来配合案件).
如果你是在UNIX-Y平台(除了窗户,基本上),你可以使用multiprocessing
,而不是threading
- 这是更强大,并允许您将信号发送到"其他处理"; SIGSTOP应该无条件地暂停一个进程,SIGCONT继续它(如果你的进程需要在它暂停之前做一些事情,还要考虑SIGTSTP信号,其他进程可以捕获它来执行这样的暂停前任务.(可能有办法获得)对Windows有同样的影响,但我不了解它们,如果有的话).
您可以使用信号:http://docs.python.org/library/signal.html#signal.pause
为了避免使用信号,您可以使用令牌传递系统。如果您想从主 UI 线程暂停它,您可能只需使用 Queue.Queue 对象与其进行通信。
只需弹出一条消息,告诉线程睡眠一定时间到队列中。
或者,您可以简单地从主 UI 线程连续将令牌推送到队列中。工作人员应该每 N 秒(0.2 或类似的时间)检查一次队列。当没有令牌可以出队时,工作线程将阻塞。当您希望它再次启动时,只需再次开始将令牌从主线程推送到队列即可。
归档时间: |
|
查看次数: |
27382 次 |
最近记录: |