python如何开启多线程
更新时间:2023年08月14日 08:39:17 作者:Audreybiubiu
这篇文章主要介绍了python如何开启多线程问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
python开启多线程
为了加快程序运行速度,对相同功能的一些执行语句,python可以通过 ThreadPool 做到
重要的函数为
pool = ThreadPool(processes=3) pool.apply_async(func, args=(**krags)) pool.close() pool.join()
from multiprocessing.pool import ThreadPool def parallel(self, cls, driven_data_key=None): if not self.FINAL_TEMPLATE: self.get_final_templates() # 开启线程池里线程的数量 pool = ThreadPool(processes=len(self.FINAL_TEMPLATE)) # 当前的for循环实则并行执行 for top_template in self.FINAL_TEMPLATE: # 第一个参数为想要并行执行的函数,第二个参数为要执行的函数所需要的参数 pool.apply_async(self.filter_case_online, args=(cls, top_template)) pool.close() pool.join()
python开启多线程/停止多线程
import ctypes
import inspect
import threading
import time
def main(a):
while True:
print(a)
class myThread(threading.Thread): # 继承父类threading.Thread
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self): # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
main(self.name)
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
if __name__ == '__main__':
nameList = [1, 2, 3, 4, 5, 6]
threadList = []
for name in nameList:
threadList.append(myThread(str(name)))
# 开启线程
for thread in threadList:
thread.start()
# 停止线程
time.sleep(1)
for thread in threadList:
stop_thread(thread)总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Python常用时间操作总结【取得当前时间、时间函数、应用等】
这篇文章主要介绍了Python常用时间操作,包括取得当前时间、时间函数、应用等概念与相关操作技巧,需要的朋友可以参考下2017-05-05
PyTorch深度学习LSTM从input输入到Linear输出
这篇文章主要为大家介绍了PyTorch深度学习LSTM从input输入到Linear输出深入理解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-05-05
pandas factorize实现将字符串特征转化为数字特征
今天小编就为大家分享一篇pandas factorize实现将字符串特征转化为数字特征,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-12-12
Python利用redis-py实现集合与有序集合的常用指令操作
这篇文章我们将来学习 redis-py 这个模块针对 “集合” 与 "有序集合"的一些常用指令操作,文中的示例代码讲解详细,需要的可以参考一下2022-09-09


最新评论