线程为什么要用队列?通过队列使线程挂起
文章目录
注意下面
如果有车载讨论需要的小伙伴,可以私信加我微信
,拉你进群,和同行业大佬交流
注意上面
前言
最近给现有测试工具上集成自动化接口测试模块,编写代码时出现一些问题,咨询大佬,得以解决,同时也指出我在线程使用上的问题,今天想在这里记录一篇相关文章,以防备以后翻阅
一、线程为什么要用队列?
我们用线程一般是用来做一些耗时且重复的事情,这时候如果不用队列的话,每一次执行重复的事就会开启一个线程,这是浪费资源的操作
1.1 不用队列的代码
from multiprocessing import Queue
import mythread
def mprintnum(num): #创建打印函数
print(num)
def print_thread(num): #创建打印线程
t1 = mythread.MyThread(target=mprintnum,args=(num,))
t1.start()
def mrange():
for num in range(10):
print_thread(num)
mrange() #运行函数
1.2运行结果
C:\Users\Administrator\AppData\Local\Programs\Python\Python310\python.exe D:/pythonproject/Queuetest.py
0
Thread-1 (mprintnum)
1
Thread-2 (mprintnum)
2
Thread-3 (mprintnum)
3
Thread-4 (mprintnum)
4
Thread-5 (mprintnum)
5
Thread-6 (mprintnum)
6
Thread-7 (mprintnum)
78
Thread-9 (mprintnum)
Thread-8 (mprintnum)
9
Thread-10 (mprintnum)
Process finished with exit code 0
这里可以看出实际是生成了10个线程
2.1使用队列的代码
import time
from multiprocessing import Queue
import mythread
class thread_test():
def __init__(self):
self.q = Queue(10) #创建队列
self.print_thread() #开启现场
def mprintnum(self): #创建打印函数
flag = 0
while flag < 11:
if not self.q.empty():
value = self.q.get()
print(value)
time.sleep(0.1)
flag+=1
def print_thread(self): #创建打印线程
t1 = mythread.MyThread(target=self.mprintnum)
t1.start()
def mrange(self,):
for num in range(10):
if not self.q.full():
self.q.put(num)
me = thread_test()
me.mrange()
2.2运行结果
C:\Users\Administrator\AppData\Local\Programs\Python\Python310\python.exe D:/pythonproject/Queuetest.py
0
1
2
3
4
5
6
7
8
9
Thread-1 (mprintnum)
Process finished with exit code 0
这里可以看出实际是生成了1个线程
综合上面部分我们可以看出,通过队列可以实现重复的事情一个线程完成,而不需要重复的生成线程去完成它
二、通过队列使线程挂起
1.用multiprocessing.Queue的挂起线程
import time
from multiprocessing import Queue
import mythread
class thread_test():
def __init__(self):
self.q = Queue(10) #创建队列
self.print_thread() #开启现场
def mprintnum(self): #创建打印函数
while True:
value = self.q.get() #因为这里是阻塞式的,所以程序会在这里阻塞,线程也就会挂起
print("the is test")
print(value)
time.sleep(0.1)
def print_thread(self): #创建打印线程
t1 = mythread.MyThread(target=self.mprintnum)
t1.start()
def mrange(self,):
for num in range(10):
if not self.q.full():
self.q.put(num) #这里的写入是阻塞式的,写入之前最好判断一下队列有没有满
me = thread_test()
me.mrange()
1.2运行结果
C:\Users\Administrator\AppData\Local\Programs\Python\Python310\python.exe D:/pythonproject/Queuetest.py
the is test
0
the is test
1
the is test
2
the is test
3
the is test
4
the is test
5
the is test
6
the is test
7
the is test
8
the is test
9
从以上代码可以看出,实际的代码用multiprocessing.Queue队列的线程,会在value = self.q.get() 这里阻塞,
这样我们就可以做到挂起线程,等需要运行时在向队列里传值运行
写在结尾
我是一名车载集成测试开发工程师,希望能和志同道合的朋友一起相互学习进步