python+Qt编写多线程的过程中,由于python和Qt都各自有各自的线程、定时器的书写方法,在此,将它整理一下。
import threading
import time
def fun(arg):
#do somthing
print('call fun(arg=%d)' % arg)
for i in range(4):
my_thread = threading.Thread(target=fun,args=(i,))
my_thread.start()
# call fun(arg=0)
# call fun(arg=1)
# call fun(arg=2)
# call fun(arg=3)
使用threading.Thread()函数创建线程,调用start()函数启动线程。
编写多线程时,必然要考虑同步互斥,要用到互斥锁、条件变量、信号量等,参考如下博文:
https://www.cnblogs.com/Security-Darren/p/4732914.html
定时器是在threading里面的一个模块,每当定时器到期,调用一个函数,有关其例子,可以看:
在隔一段时间就抓取保存照片的程序中,简单的方法,就可以利用定时器,每隔一段时间启用线程,查看当前时间是否满足要求,满足则保存图片
import threading
import time
def fun(arg):
#判断并抓取图片
print('call fun(arg=%d)' % arg)
my_thread = threading.Timer(5, fun, args=[arg+1,])#每隔5秒重新启动该线程
my_thread.start()
fun(1)
# call fun(arg=1)
# call fun(arg=2)
# call fun(arg=3)
# call fun(arg=4)
# call fun(arg=5)
在PyQt5.QtCore模块中,有一个QThread,Qt的线程是跑Application上的,也就是说,没有调用Application的exec_()循环函数,是测试不了QThread的,但是QThread的使用方法,和Python中的threading.Thread是一样的,所以,在此先给出重写threading.Thread的测试
import threading
class PyThread(threading.Thread):
def __init__(self):
super(PyThread,self).__init__()
#重写run函数,实现线程的工作
def run(self):
#do something
print("call pythonThread fun")
my_thread = PyThread()
my_thread.start()
#call pythonThread fun
pyqt5的写法:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class QtThread(QThread):
def __init__(self):
super(QtThread,self).__init__()
#重写run函数,实现线程的工作
def run(self):
#do something
print("call pyqt5Thread fun")
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(500,300,300,300)
self.thread = QtThread()
self.thread.start()
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setApplicationName("测试")
window = MainWindow()
window.show()
sys.exit(app.exec_())
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class QtThread(QThread):
def __init__(self):
super(QtThread,self).__init__()
#重写run函数,实现线程的工作
def run(self):
#do something
print("call pyqt5Thread fun")
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(500,300,300,300)
self.thread = QtThread()
self.thread.start()
self.timer = QTimer()
self.timer.start(5000) #每过5秒,定时器到期,产生timeout的信号
self.timer.timeout.connect(self.call_thread)
def call_thread(self):
self.thread = QtThread()
self.thread.start()
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setApplicationName("测试")
window = MainWindow()
window.show()
sys.exit(app.exec_())