python 多線程應用介紹
更新時間:2012年12月19日 23:17:50 投稿:mdxy-dxy
python可以方便地支持多線程??梢钥焖賱?chuàng)建線程、互斥鎖、信號量等等元素,支持線程讀寫同步互斥
python可以方便地支持多線程??梢钥焖賱?chuàng)建線程、互斥鎖、信號量等等元素,支持線程讀寫同步互斥。美中不足的是,python的運行在python 虛擬機上,創(chuàng)建的多線程可能是虛擬的線程,需要由python虛擬機來輪詢調度,這大大降低了python多線程的可用性。我們經今天用了經典的生產者和消費者的問題來說明下python的多線程的運用 上代碼:
#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()
你親自運行下這斷代碼,可能有不一樣的感覺!理解以后可以用python cookielib 再結果python urllib 寫一個多線程下載網頁的腳本應該沒什么問題
相關文章
python可擴展的Blender 3D插件開發(fā)匯總
這篇文章主要為大家介紹了python可擴展的Blender 3D插件開發(fā)匯總,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
ubuntu在線服務器python?Package安裝到離線服務器的過程
這篇文章主要介紹了ubuntu在線服務器python?Package安裝到離線服務器,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04

