思路
借助python當中threading模塊與Queue模塊組合可以方便的實現(xiàn)基于生產(chǎn)者-消費者模型的多線程模型。Jimmy大神的tushare一直是廣大python數(shù)據(jù)分析以及業(yè)余量化愛好者喜愛的免費、開源的python財經(jīng)數(shù)據(jù)接口包。
平時一直有在用阿里云服務(wù)器通過tushare的接口自動落地相關(guān)財經(jīng)數(shù)據(jù),但日復權(quán)行情數(shù)據(jù)以往在串行下載的過程當中,速度比較慢,有時遇到網(wǎng)絡(luò)原因還需要重下。每只股票的行情下載過程中都需要完成下載、落地2個步驟,一個可能需要網(wǎng)絡(luò)開銷、一個需要數(shù)據(jù)庫mysql的存取開銷。2者原本就可以獨立并行執(zhí)行,是個典型的“生產(chǎn)者-消費者”模型。
基于queue與threading模塊的線程使用一般采用以下的套路:
producerQueue=Queue()consumerQueue=Queue()lock = threading.Lock()class producerThead(threading.Thread): def __init__(self, producerQueue,consumerQueue): self.producerQueue=producerQueue self.consumerQueue=consumerQueue def run(self): while not self.thread_stop: try: #接收任務(wù),如果連續(xù)20秒沒有新的任務(wù),線程退出,否則會一直執(zhí)行 item=self.producerQueue.get(block=True, timeout=20) #阻塞調(diào)用進程直到有數(shù)據(jù)可用。如果timeout是個正整數(shù), #阻塞調(diào)用進程最多timeout秒, #如果一直無數(shù)據(jù)可用,拋出Empty異常(帶超時的阻塞調(diào)用) except Queue.Empty: print("Nothing to do!thread exit!") self.thread_stop=True break #實現(xiàn)生產(chǎn)者邏輯,生成消費者需要處理的內(nèi)容 consumerQueue.put(someItem) #還可以邊處理,邊生成新的生產(chǎn)任務(wù) doSomethingAboutProducing() self.producerQueue.task_done() def stop(self): self.thread_stop = Trueclass consumerThead(threading.Thread): def __init__(self,lock, consumerQueue): self.consumerQueue=consumerQueue def run(self): while true: try: #接收任務(wù),如果連續(xù)20秒沒有新的任務(wù),線程退出,否則會一直執(zhí)行 item=self.consumerQueue.get(block=True, timeout=20) #阻塞調(diào)用進程直到有數(shù)據(jù)可用。如果timeout是個正整數(shù), #阻塞調(diào)用進程最多timeout秒, #如果一直無數(shù)據(jù)可用,拋出Empty異常(帶超時的阻塞調(diào)用) except Queue.Empty: print("Nothing to do!thread exit!") self.thread_stop=True break doSomethingAboutConsuming(lock)# 處理消費者邏輯,必要時使用線程鎖 ,如文件操作等 self.consumerQueue.task_done()#定義主線程def main(): for i in range(n):#定義n個i消費者線程 t = ThreadRead(producerQueue, consumerQueue) t.setDaemon(True) t.start() producerTasks=[] #定義初始化生產(chǎn)者任務(wù)隊列 producerQueue.put(producerTasks) for i in range(n):#定義n個生產(chǎn)者錢程 t = ThreadWrite(consumerQueue, lock) t.setDaemon(True) t.start() stock_queue.join() data_queue.join()相關(guān)接口
1,股票列表信息接口
作用
獲取滬深上市公司基本情況。屬性包括:
新聞熱點
疑難解答
圖片精選