[英]How to pause a thread (python)
上下文:我正在使用Qt创建器和python中的“行为”文件构建图形界面。 我的GUI的测试版本是:
预期的行为:我正在运行2个不同的线程,这些线程使用不同的输入参数引用同一函数。 使用SELECTOR按钮,我可以将1或2的值分配给变量(并显示该变量)。按钮Start thread可以启动正确的线程(第一次)。 通过修改全局running
变量,可以通过停止按钮关闭循环。 这是我的代码
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui, uic
import sys
import threading
import time
import Queue
running = False
first_thread = None
second_thread = None
form_class = uic.loadUiType("simple2.ui")[0]
q = Queue.Queue()
select = 0
def action(string, queue): #function called by threads
global running
while(running):
phrase = string
if queue.qsize() < 10:
queue.put(phrase)
#else:
# print queue.qsize()
class MyWindowClass(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
#buttons
self.startButton.clicked.connect(self.start_clicked)
self.stopButton.clicked.connect(self.stop_clicked)
self.selector.clicked.connect(self.sel_click)
#variables
self.first = False
self.second = False
#queue
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.update_phrase)
self.timer.start(1)
def start_clicked(self): #start button callback
global select
if select > 0:
global running
running = True
print "started"
if (not self.first) & (select == 1):
first_thread.start()
self.first = True
if (not self.second) & (select == 2):
second_thread.start()
self.second = True
self.startButton.setEnabled(False)
self.startButton.setText('Starting...')
def stop_clicked(self): #stop button callback
global running
running = False
print "stopped"
self.startButton.setEnabled(True)
self.startButton.setText('Start Thread')
def sel_click(self): #selector button callback
global select
if select < 2:
select = select + 1
else:
select = 1
self.thread_counter.setText(str(select))
def update_phrase(self): #looping function
global running
if (not q.empty()) & running:
self.startButton.setText('Thread on')
abc = q.get()
print abc
def closeEvent(self, event):
global running
running = False
if __name__ == "__main__":
first_thread = threading.Thread(target=action, args = ("first", q))
second_thread = threading.Thread(target=action, args = ("second", q))
app = QtGui.QApplication(sys.argv)
w = MyWindowClass(None)
w.setWindowTitle('Multiple threads test in python')
w.show()
app.exec_()
现在,每个线程应该在终端上简单地打印其参数(“ First”或“ Second”)。 如果是第一次启动线程,则我的代码有效。 但是我想在线程之间无限次切换。
由于无法停止线程,有没有办法“暂停”它们?
我找不到解决方案,希望有人也能帮我提供一段代码。 先感谢您
您可以使用Lock类来做到这一点,一个简单的例子是:
import threading
lock = threading.Lock()
//here it will be lock
lock.acquire() # will block if lock is already held
...
然后在另一边
//this will wake up
lock.release()
您可以在此处了解更多信息http://effbot.org/zone/thread-synchronization.htm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.