简单明了的 Python 多线程来了
多线程:允许单个任务分成不同的部分运行
import time
def run(n):
print("task", n)
time.sleep(1) #延时一秒
print('2s')
time.sleep(1)
print('1s')
time.sleep(1)
print('0s')
time.sleep(1)
if __name__ == '__main__':
t1 = threading.Thread(target=run, args=("t1",))#创建线程1,取名为t1
t2 = threading.Thread(target=run, args=("t2",))#创建线程2,取名为t2
t1.start() #开启线程t1
t2.start() #开启线程t2
task t2
2s
2s
1s
1s
0s
0s
import time
class MyThread(threading.Thread):
def __init__(self, n):
super(MyThread, self).__init__() # 重构run函数必须要写
self.n = n
def run(self):
print("task", self.n)
time.sleep(1)
print('2s')
time.sleep(1)
print('1s')
time.sleep(1)
print('0s')
time.sleep(1)
if __name__ == "__main__":
t1 = MyThread("t1")
t2 = MyThread("t2")
t1.start()
t2.start()
task t2
2s
2s
1s
1s
0s
0s
import time
def run(n):
print("task", n)
time.sleep(1) #此时子线程停1s
print('3')
time.sleep(1)
print('2')
time.sleep(1)
print('1')
if __name__ == '__main__':
t = threading.Thread(target=run, args=("t1",))
t.setDaemon(True) #把子进程设置为守护线程,必须在start()之前设置
t.start()
print("end")
end
import time
def run(n):
print("task", n)
time.sleep(1)
print('3')
time.sleep(1)
print('2')
time.sleep(1)
print('1')
if __name__ == '__main__':
t = threading.Thread(target=run, args=("t1",))
t.setDaemon(True) #把子进程设置为守护线程,必须在start()之前设置
t.start()
t.join() # 设置主线程等待子线程结束
print("end")
3
2
1
end
import time
num = 100
def work1():
global num
for i in range(3):
num += 1
print("in work1 num is : %d" % num)
def work2():
global num
print("in work2 num is : %d" % num)
if __name__ == '__main__':
t1 = threading.Thread(target=work1)
t1.start()
time.sleep(1)
t2 = threading.Thread(target=work2)
t2.start()
in work2 num is : 103
def work1():
global A,lock#定义A和lock为全局变量
lock.acquire()#上锁
for i in range(5):
A+=1
print('work1',A)
lock.release()#解锁
def work2():
global A,lock
lock.acquire()
for i in range(5):
A+=10
print('work2',A)
lock.release()
if __name__=='__main__':
lock=threading.Lock()#定义锁
A=0
t1=threading.Thread(target=work1)
t2=threading.Thread(target=work2)
t1.start()
t2.start()
t1.join()
t2.join()
work1 2
work1 3
work1 4
work1 5
work2 15
work2 25
work2 35
work2 45
work2 55
import time
def Func(lock):
global gl_num
lock.acquire()
gl_num += 1
time.sleep(1)
print(gl_num)
lock.release()
if __name__ == '__main__':
gl_num = 0
lock = threading.RLock()
for i in range(10):
t = threading.Thread(target=Func, args=(lock,))
t.start()
2
3
4
5
6
7
8
9
10
import time
def run(n, semaphore):
semaphore.acquire() #加锁
time.sleep(1)
print("run the thread:%s\n" % n)
semaphore.release() #释放
if __name__ == '__main__':
num = 0
semaphore = threading.BoundedSemaphore(5) # 最多允许5个线程同时运行
for i in range(22):
t = threading.Thread(target=run, args=("t-%s" % i, semaphore))
t.start()
while threading.active_count() != 1:
pass # print threading.active_count()
else:
print('-----all threads done-----')
clear 将flag设置为“False”; set 将flag设置为“True”; is_set 判断是否设置了flag; wait 会一直监听flag,如果没有检测到flag就一直处于阻塞状态。
import time
event = threading.Event()
def lighter():
count = 0
event.set() #初始值为绿灯
while True:
if 5 < count <=10 :
event.clear() # 红灯,清除标志位
print("1mred light is on...")
elif count > 10:
event.set() # 绿灯,设置标志位
count = 0
else:
print("mgreen light is on...")
time.sleep(1)
count += 1
def car(name):
while True:
if event.is_set(): #判断是否设置了标志位
print("[%s] running..."%name)
time.sleep(1)
else:
print("[%s] sees red light,waiting..."%name)
event.wait()
print("[%s] green light is on,start going..."%name)
light = threading.Thread(target=lighter,)
light.start()
car = threading.Thread(target=car,args=("MINI",))
car.start()
QThread只有run函数是在新线程里的; QThread只有run函数是在新线程里的; QThread只有run函数是在新线程里的。
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
count = 0
# 工作线程
class WorkThread(QThread):
# pyqtSignal是信号类
timeout = pyqtSignal() # 每隔一秒发送一个信号
end = pyqtSignal() # 计数完成后发送一个信号
def run(self):
while True:
# 休眠1秒
self.sleep(1)
if count == 5:
self.end.emit() # 发送end信号,调用和end信号关联的方法
break
self.timeout.emit() # 发送timeout信号
class Counter(QWidget):
def __init__(self):
super(Counter, self).__init__()
self.setWindowTitle("用QThread编写计数器")
self.resize(600, 400)
layout = QVBoxLayout()
# QLCDNumber 用于模拟LED显示效果,类似于Label
self.lcdNumber = QLCDNumber()
layout.addWidget(self.lcdNumber)
button = QPushButton("开始计数")
layout.addWidget(button)
self.workThread = WorkThread()
self.workThread.timeout.connect(self.countTime)
self.workThread.end.connect(self.end)
button.clicked.connect(self.work)
self.setLayout(layout)
def countTime(self):
global count
count += 1
self.lcdNumber.display(count)
def end(self):
QMessageBox.information(self, '消息', '计数结束', QMessageBox.Ok)
global count
count =0
def work(self):
self.workThread.start()
if __name__ == "__main__":
app = QApplication(sys.argv)
main = Counter()
main.show()
sys.exit(app.exec_())
while(mode):
self.sleep(1)