欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python如何開啟多線程

 更新時(shí)間:2023年08月14日 08:39:17   作者:Audreybiubiu  
這篇文章主要介紹了python如何開啟多線程問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

python開啟多線程

為了加快程序運(yùn)行速度,對(duì)相同功能的一些執(zhí)行語句,python可以通過 ThreadPool 做到

重要的函數(shù)為

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()
? ? # 開啟線程池里線程的數(shù)量
? ? pool = ThreadPool(processes=len(self.FINAL_TEMPLATE))
? ? # 當(dāng)前的for循環(huán)實(shí)則并行執(zhí)行
? ? for top_template in self.FINAL_TEMPLATE:
? ? ?? ?# 第一個(gè)參數(shù)為想要并行執(zhí)行的函數(shù),第二個(gè)參數(shù)為要執(zhí)行的函數(shù)所需要的參數(shù)
? ? ? ? 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):  # 把要執(zhí)行的代碼寫到run函數(shù)里面 線程在創(chuàng)建后會(huì)直接運(yùn)行run函數(shù)
        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)

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論