python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python开启多线程

python如何开启多线程

作者: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)

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文