python 多線程應(yīng)用介紹
python可以方便地支持多線程??梢钥焖賱?chuàng)建線程、互斥鎖、信號量等等元素,支持線程讀寫同步互斥。美中不足的是,python的運(yùn)行在python 虛擬機(jī)上,創(chuàng)建的多線程可能是虛擬的線程,需要由python虛擬機(jī)來輪詢調(diào)度,這大大降低了python多線程的可用性。我們經(jīng)今天用了經(jīng)典的生產(chǎn)者和消費(fèi)者的問題來說明下python的多線程的運(yùn)用 上代碼:
#encoding=utf-8
import threading
import random
import time
from Queue import Queue
class Producer(threading.Thread):
def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue
def run(self):
for i in range(20):
print self.getName(),'adding',i,'to queue'
self.sharedata.put(i)
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'
# Consumer thread
class Consumer(threading.Thread):
def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue
def run(self):
for i in range(20):
print self.getName(),'got a value:',self.sharedata.get()
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'
# Main thread
def main():
queue = Queue()
producer = Producer('Producer', queue)
consumer = Consumer('Consumer', queue)
print 'Starting threads ...'
producer.start()
consumer.start()
producer.join()
consumer.join()
print 'All threads have terminated.'
if __name__ == '__main__':
main()
你親自運(yùn)行下這斷代碼,可能有不一樣的感覺!理解以后可以用python cookielib 再結(jié)果python urllib 寫一個(gè)多線程下載網(wǎng)頁的腳本應(yīng)該沒什么問題
- python多線程編程中的join函數(shù)使用心得
- python中的多線程實(shí)例教程
- Python中多線程thread與threading的實(shí)現(xiàn)方法
- python實(shí)現(xiàn)多線程采集的2個(gè)代碼例子
- Python實(shí)現(xiàn)多線程下載文件的代碼實(shí)例
- python多線程抓取天涯帖子內(nèi)容示例
- Python使用代理抓取網(wǎng)站圖片(多線程)
- python支持?jǐn)帱c(diǎn)續(xù)傳的多線程下載示例
- python多線程掃描端口示例
- python多線程http下載實(shí)現(xiàn)示例
- python多線程編程方式分析示例詳解
- Python多線程學(xué)習(xí)資料
- Python多線程實(shí)例教程
相關(guān)文章
一篇文章告訴你如何用python進(jìn)行自動化測試,調(diào)用c程序
這篇文章主要介紹了Python實(shí)現(xiàn)性能自動化測試調(diào)用c程序的方法,本文圖文并茂通過實(shí)例代碼相結(jié)合的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2021-08-08
Python常見數(shù)據(jù)類型轉(zhuǎn)換操作示例
這篇文章主要介紹了Python常見數(shù)據(jù)類型轉(zhuǎn)換操作,結(jié)合實(shí)例形式分析了Python針對列表、集合、元組、字典等數(shù)據(jù)類型轉(zhuǎn)換的相關(guān)操作技巧,需要的朋友可以參考下2019-05-05
Python批量刪除mysql中千萬級大量數(shù)據(jù)的腳本分享
這篇文章主要介紹了Python批量刪除mysql中千萬級大量數(shù)據(jù)的示例代碼,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12
對Pandas DataFrame缺失值的查找與填充示例講解
今天小編就為大家分享一篇對Pandas DataFrame缺失值的查找與填充示例講解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11
Python RuntimeError: thread.__init__() not called解決方法
這篇文章主要介紹了Python RuntimeError: thread.__init__() not called解決方法,需要的朋友可以參考下2015-04-04

