python下線程以及鎖

來源:互聯網
上載者:User

標籤:

1、python多線程

 1 #encoding=utf-8 2 """ 3 python多線程,並非真正意義上的多線程 4 全域鎖:在指定時間裡,有且只有一個線程在運行 5  6  7 """ 8 import threading 9 import time10 11 def test(p):12     time.sleep(0.1)13     print p14 15 # a = threading.Thread(target=test)16 # b = threading.Thread(target=test)17 # a.start()18 # b.start()19 # 20 # a.join()21 # b.join()22 23 lst =[]24 for i in xrange(0, 15):25     th = threading.Thread(target=test, args=[i])26     lst.append(th)27 28 for i in lst:29     i.start()30 31 32 for i in lst:33     i.join()34 print "primary thread end!!!"

2、python下的鎖

 1 #encoding=utf-8 2  3 """ 4 1、python全域鎖:GLT 5   python多線程在任意時刻下只有一個線程在運行,它是安全執行緒的 6 """ 7  8 import threading 9 10 num = 011 def t():12     global num13     num +=114     print num15     16 for i in xrange(0, 10):17     d = threading.Thread(target=t)18     d.start()19 20 21 import time22 b_time = time.time()23 _a = threading.Thread(target=t)24 _b = threading.Thread(target=t)25 _a.start()26 _b.start()27 28 _a.join()29 _b.join()30 31 print time.time()-b_time32 33 """34 加鎖:acquire()35 解鎖:release()36 RLock()可重新進入鎖37 38 39 """40 import threading41 mlock = threading.Lock()42 #mlock = threading.RLock()43 44 num_01 = 045 def a():46     global num_0147     mlock.acquire()48     num_01 += 149     mlock.release()50     print num_0151     52 for i in xrange(0, 10):53     d = threading.Thread(target=a)54     d.start()55     

 

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.