python如何開啟多線程
更新時間:2023年08月14日 08:39:17 作者:Audreybiubiu
這篇文章主要介紹了python如何開啟多線程問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
python開啟多線程
為了加快程序運行速度,對相同功能的一些執(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)) ? ? # 當前的for循環(huán)實則并行執(zhí)行 ? ? for top_template in self.FINAL_TEMPLATE: ? ? ?? ?# 第一個參數(shù)為想要并行執(zhí)行的函數(shù),第二個參數(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)建后會直接運行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)總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python基于callable函數(shù)檢測對象是否可被調(diào)用
這篇文章主要介紹了Python基于callable函數(shù)檢測對象是否可被調(diào)用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-10-10
Python中使用 Selenium 實現(xiàn)網(wǎng)頁截圖實例
這篇文章主要介紹了Python中使用 Selenium 實現(xiàn)網(wǎng)頁截圖實例,Selenium支持Java、C#、Ruby 以及 Python等語言,本文以Python語言為例,需要的朋友可以參考下2014-07-07
python 批量修改 labelImg 生成的xml文件的方法
這篇文章主要介紹了python 批量修改 labelImg 生成的xml文件的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09
Django數(shù)據(jù)庫操作之save與update的使用
這篇文章主要介紹了Django數(shù)據(jù)庫操作之save與update的使用,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Jupyter Notebook 實現(xiàn)正常顯示中文和負號
這篇文章主要介紹了Jupyter Notebook 實現(xiàn)正常顯示中文和負號,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
python實現(xiàn)數(shù)通設備端口監(jiān)控示例
這篇文章主要介紹了python實現(xiàn)數(shù)通設備端口監(jiān)控示例,需要的朋友可以參考下2014-04-04

