python中threading和queue庫實(shí)現(xiàn)多線程編程
本文主要介紹了利用python的 threading和queue庫實(shí)現(xiàn)多線程編程,并封裝為一個(gè)類,方便讀者嵌入自己的業(yè)務(wù)邏輯。最后以機(jī)器學(xué)習(xí)的一個(gè)超參數(shù)選擇為例進(jìn)行演示。
多線程實(shí)現(xiàn)邏輯封裝實(shí)例化該類后,在.object_func函數(shù)中加入自己的業(yè)務(wù)邏輯,再調(diào)用.run方法即可。
# -*- coding: utf-8 -*-# @Time : 2021/2/4 14:36# @Author : CyrusMay WJ# @FileName: run.py# @Software: PyCharm# @Blog :https://blog.csdn.net/Cyrus_Mayimport queueimport threadingclass CyrusThread(object): def __init__(self,num_thread = 10,logger=None): ''':param num_thread: 線程數(shù) :param logger: 日志對象 ''' self.num_thread = num_thread self.logger = logger def object_func(self,args_queue,max_q): while 1: try:arg = args_queue.get_nowait()step = args_queue.qsize()self.logger.info('progress:{}{}'.format(max_q,step)) except:self.logger.info('no more arg for args_queue!')break'''此處加入自己的業(yè)務(wù)邏輯代碼''' def run(self,args): args_queue = queue.Queue() for value in args: args_queue.put(value) threads = [] for i in range(self.num_thread): threads.append(threading.Thread(target=self.object_func,args = args_queue)) for t in threads: t.start() for t in threads: t.join()
模型參數(shù)選擇實(shí)例
# -*- coding: utf-8 -*-# @Time : 2021/2/4 14:36# @Author : CyrusMay WJ# @FileName: run.py# @Software: PyCharm# @Blog :https://blog.csdn.net/Cyrus_Mayimport queueimport threadingimport numpy as npfrom sklearn.datasets import load_bostonfrom sklearn.svm import SVRimport loggingimport sysclass CyrusThread(object): def __init__(self,num_thread = 10,logger=None): ''' :param num_thread: 線程數(shù) :param logger: 日志對象 ''' self.num_thread = num_thread self.logger = logger def object_func(self,args_queue,max_q): while 1: try:arg = args_queue.get_nowait()step = args_queue.qsize()self.logger.info('progress:{}{}'.format(max_q,max_q-step)) except:self.logger.info('no more arg for args_queue!')break # 業(yè)務(wù)代碼 C, epsilon, gamma = arg[0], arg[1], arg[2] svr_model = SVR(C=C, epsilon=epsilon, gamma=gamma) x, y = load_boston()['data'], load_boston()['target'] svr_model.fit(x, y) self.logger.info('score:{}'.format(svr_model.score(x,y))) def run(self,args): args_queue = queue.Queue() max_q = 0 for value in args: args_queue.put(value) max_q += 1 threads = [] for i in range(self.num_thread): threads.append(threading.Thread(target=self.object_func,args = (args_queue,max_q))) for t in threads: t.start() for t in threads: t.join()# 創(chuàng)建日志對象logger = logging.getLogger()logger.setLevel(logging.INFO)screen_handler = logging.StreamHandler(sys.stdout)screen_handler.setLevel(logging.INFO)formatter = logging.Formatter(’%(asctime)s - %(module)s.%(funcName)s:%(lineno)d - %(levelname)s - %(message)s’)screen_handler.setFormatter(formatter)logger.addHandler(screen_handler)# 創(chuàng)建需要調(diào)整參數(shù)的集合args = []for C in [i for i in np.arange(0.01,1,0.01)]: for epsilon in [i for i in np.arange(0.001,1,0.01)] + [i for i in range(1,10,1)]: for gamma in [i for i in np.arange(0.001,1,0.01)] + [i for i in range(1,10,1)]: args.append([C,epsilon,gamma])# 創(chuàng)建多線程工具threading_tool = CyrusThread(num_thread=20,logger=logger)threading_tool.run(args)
運(yùn)行結(jié)果
2021-02-04 20:52:22,824 - run.object_func:31 - INFO - progress:117621912021-02-04 20:52:22,824 - run.object_func:31 - INFO - progress:117621922021-02-04 20:52:22,826 - run.object_func:31 - INFO - progress:117621932021-02-04 20:52:22,833 - run.object_func:31 - INFO - progress:117621942021-02-04 20:52:22,837 - run.object_func:31 - INFO - progress:117621952021-02-04 20:52:22,838 - run.object_func:31 - INFO - progress:117621962021-02-04 20:52:22,841 - run.object_func:31 - INFO - progress:117621972021-02-04 20:52:22,862 - run.object_func:31 - INFO - progress:117621982021-02-04 20:52:22,873 - run.object_func:31 - INFO - progress:117621992021-02-04 20:52:22,884 - run.object_func:31 - INFO - progress:1176219102021-02-04 20:52:22,885 - run.object_func:31 - INFO - progress:1176219112021-02-04 20:52:22,897 - run.object_func:31 - INFO - progress:1176219122021-02-04 20:52:22,900 - run.object_func:31 - INFO - progress:1176219132021-02-04 20:52:22,904 - run.object_func:31 - INFO - progress:1176219142021-02-04 20:52:22,912 - run.object_func:31 - INFO - progress:1176219152021-02-04 20:52:22,920 - run.object_func:31 - INFO - progress:1176219162021-02-04 20:52:22,920 - run.object_func:39 - INFO - score:-0.016742839142878552021-02-04 20:52:22,929 - run.object_func:31 - INFO - progress:1176219172021-02-04 20:52:22,932 - run.object_func:39 - INFO - score:-0.0079923541709525652021-02-04 20:52:22,932 - run.object_func:31 - INFO - progress:1176219182021-02-04 20:52:22,945 - run.object_func:31 - INFO - progress:1176219192021-02-04 20:52:22,954 - run.object_func:31 - INFO - progress:1176219202021-02-04 20:52:22,978 - run.object_func:31 - INFO - progress:1176219212021-02-04 20:52:22,984 - run.object_func:39 - INFO - score:-0.0187699348072465362021-02-04 20:52:22,985 - run.object_func:31 - INFO - progress:117621922
到此這篇關(guān)于python中threading和queue庫實(shí)現(xiàn)多線程編程的文章就介紹到這了,更多相關(guān)python 多線程編程內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 如何基于Python Matplotlib實(shí)現(xiàn)網(wǎng)格動(dòng)畫2. 利用promise及參數(shù)解構(gòu)封裝ajax請求的方法3. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向4. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明5. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測可用)6. Ajax實(shí)現(xiàn)表格中信息不刷新頁面進(jìn)行更新數(shù)據(jù)7. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析8. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無效問題9. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法10. PHP設(shè)計(jì)模式中工廠模式深入詳解
