python實現(xiàn)線程池的方法
本文實例講述了python實現(xiàn)線程池的方法。分享給大家供大家參考。具體如下:
原理:建立一個任務隊列,然多個線程都從這個任務隊列中取出任務然后執(zhí)行,當然任務隊列要加鎖,詳細請看代碼
文件名:thrd_pool.py 系統(tǒng)環(huán)境:ubuntu linux & python2.6
import threading import time import signal import os class task_info(object): def __init__(self): self.func = None self.parm0 = None self.parm1 = None self.parm2 = None class task_list(object): def __init__(self): self.tl = [] self.mutex = threading.Lock() self.sem = threading.Semaphore(0) def append(self, ti): self.mutex.acquire() self.tl.append(ti) self.mutex.release() self.sem.release() def fetch(self): self.sem.acquire() self.mutex.acquire() ti = self.tl.pop(0) self.mutex.release() return ti class thrd(threading.Thread): def __init__(self, tl): threading.Thread.__init__(self) self.tl = tl def run(self): while True: tsk = self.tl.fetch() tsk.func(tsk.parm0, tsk.parm1, tsk.parm2) class thrd_pool(object): def __init__(self, thd_count, tl): self.thds = [] for i in range(thd_count): self.thds.append(thrd(tl)) def run(self): for thd in self.thds: thd.start() def func(parm0=None, parm1=None, parm2=None): print 'count:%s, thrd_name:%s'%(str(parm0), threading.currentThread().getName()) def cleanup(signo, stkframe): print ('Oops! Got signal %s', signo) os._exit(0) if __name__ == '__main__': signal.signal(signal.SIGINT, cleanup) signal.signal(signal.SIGQUIT, cleanup) signal.signal(signal.SIGTERM, cleanup) tl = task_list() tp = thrd_pool(6, tl) tp.run() count = 0 while True: ti = task_info() ti.parm0 = count ti.func = func tl.append(ti) count += 1 time.sleep(2) pass
執(zhí)行方式:python thrd_pool.py
執(zhí)行結(jié)果:
count:0, thrd_name:Thread-1 count:1, thrd_name:Thread-2 count:2, thrd_name:Thread-3 count:3, thrd_name:Thread-4 count:4, thrd_name:Thread-5 count:5, thrd_name:Thread-1 count:6, thrd_name:Thread-6 count:7, thrd_name:Thread-2 count:8, thrd_name:Thread-3 count:9, thrd_name:Thread-4 count:10, thrd_name:Thread-5 count:11, thrd_name:Thread-1 count:12, thrd_name:Thread-6 count:13, thrd_name:Thread-2 count:14, thrd_name:Thread-3 ('Oops! Got signal %s', 15)
希望本文所述對大家的Python程序設(shè)計有所幫助。
相關(guān)文章
使用 Visual Studio Code(VSCode)搭建簡單的Python+Django開發(fā)環(huán)境的方法步驟
這篇文章主要介紹了使用 Visual Studio Code(VSCode)搭建簡單的Python+Django開發(fā)環(huán)境的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12利用python對Excel中的特定數(shù)據(jù)提取并寫入新表的方法
今天小編就為大家分享一篇利用python對Excel中的特定數(shù)據(jù)提取并寫入新表的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06python3.7安裝matplotlib失敗問題的完美解決方法
由于學習需要安裝matplotlib庫,閱讀網(wǎng)上教程后一直出現(xiàn)各種各樣的錯誤,下面這篇文章主要給大家介紹了關(guān)于python3.7安裝matplotlib失敗問題的完美解決方法,需要的朋友可以參考下2022-07-07python GUI庫圖形界面開發(fā)之PyQt5表單布局控件QFormLayout詳細使用方法與實例
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5布局控件QFormLayout詳細使用方法與實例,需要的朋友可以參考下2020-03-03