python線程編程

來源:互聯網
上載者:User

標籤:線程   安全執行緒   編寫自己線程類   

1、線程模式代碼

#!/usr/bin/python#_*_coding:utf-8_*_import threadingimport timedef Producer():    print ‘chef : 等人來買包子。。。‘    event.wait()    event.clear()    print ‘sb is coning for baozi...‘    print ‘chef : making a baozi for sb...‘    time.sleep(3)    print ‘chef : 你的包子好了‘    event.set()def Consumer():    print ‘maxi : 去買包子‘    event.set()    time.sleep(1)    print ‘maxi : waiting for baozi tobe readly‘    event.wait()    print ‘哎呀,真好吃‘event = threading.Event()p = threading.Thread(target=Producer)c = threading.Thread(target=Consumer)p.start()c.start()

運行結果:

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/89/7B/wKiom1gUtqmACP2oAABMPoStUdw141.png-wh_500x0-wm_3-wmp_4-s_4076459701.png" title="QQ20161029224807.png" alt="wKiom1gUtqmACP2oAABMPoStUdw141.png-wh_50" />


2、怎樣調用自己的線程類

代碼如下:

#!/usr/bin/python#_*_coding:utf-8_*_from threading import Threadimport timeclass MyThread(Thread):  #調用我自己的線程方法前,必須先調用父類的run()方法;    def run(self):        print ‘myThread‘        #Thread.run(self) #啟用父類的run(),只有這樣才能調用自己的線程函數        super(MyThread, self).run()def Bar():    print ‘bar‘,t1 = MyThread(target = Bar)  #我的線程方法Bar()函數;t1.start()print ‘over‘

運行結果:

650) this.width=650;" src="http://s1.51cto.com/wyfs02/M02/89/7B/wKiom1gUuKDRrmH0AAAjRKUvsbg297.png-wh_500x0-wm_3-wmp_4-s_2938423919.png" title="QQ20161029225631.png" alt="wKiom1gUuKDRrmH0AAAjRKUvsbg297.png-wh_50" />


3、安全執行緒

代碼如下:

#!/usr/bin/python#_*_coding:utf-8_*_import threadingimport timenum = 0 def run(n):     time.sleep(1)    samp.acquire()  #鎖上    global num     num += 1    print ‘%d\n‘ % num     samp.release()  #釋放鎖#lock = threading.Lock()  #鎖機制,samp = threading.BoundedSemaphore(4) #訊號量for i in range(1000):    t = threading.Thread(target = run, args = (i,))    t.start()

因為上面給了4個訊號量,就是可以同時最多有4個進程搶佔資源;

運行結果:

650) this.width=650;" src="http://s1.51cto.com/wyfs02/M01/89/80/wKioL1gV1c_Su7gFAAAruRTW6Gw204.png-wh_500x0-wm_3-wmp_4-s_3159204094.png" title="QQ20161030191309.png" alt="wKioL1gV1c_Su7gFAAAruRTW6Gw204.png-wh_50" />

當我們把訊號量改為1時,就相當於獨佔,此時結果肯定就是1000了;

650) this.width=650;" src="http://s2.51cto.com/wyfs02/M01/89/82/wKiom1gV1mOy3H0uAAAkWqqqgcE402.png-wh_500x0-wm_3-wmp_4-s_2536936267.png" title="QQ20161030191517.png" alt="wKiom1gV1mOy3H0uAAAkWqqqgcE402.png-wh_50" />




本文出自 “11586096” 部落格,請務必保留此出處http://11596096.blog.51cto.com/11586096/1867424

python線程編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.