Python實戰之多線程編程thread模組

來源:互聯網
上載者:User

在Python中除了可以通過繼承threading.Thread類來實現多線程外,也可以調用thread模組中的start_new_thread()函數來產生新的線程,如下

import time, thread def timer(): print('hello') def test(): for i in range(0, 10): thread.start_new_thread(timer, ()) if __name__=='__main__': test() time.sleep(10) 

或者

import time, thread def timer(name=None, group=None): print('name: ' + name + ', group: ' + group) def test(): for i in range(0, 10): thread.start_new_thread(timer, ('thread' + str(i), 'group' + str(i))) if __name__=='__main__': test() time.sleep(10) 

這個是thread.start_new_thread(function,args[,kwargs])函數原型,其中function參數是你將要調用的線程函數;args是講傳遞給你的線程函數的參數,他必須是個tuple類型;而kwargs是可選的參數。線程的結束一般依靠線程函數的自然結束;也可以線上程函數中調用thread.exit(),他拋出SystemExit exception,達到退出線程的目的。

 

下面來看一下thread中的鎖機制,如下兩段代碼:

代碼一

import time, thread count = 0 def test(): global count for i in range(0, 10000): count += 1 for i in range(0, 10): thread.start_new_thread(test, ()) time.sleep(5) print count 

代碼二

import time, thread count = 0 lock = thread.allocate_lock() def test(): global count, lock lock.acquire() for i in range(0, 10000): count += 1 lock.release() for i in range(0, 10): thread.start_new_thread(test, ()) time.sleep(5) print count 

代碼一中的值由於沒有使用lock機制,所以是多線程同時訪問全域的count變數,導致最終的count結果不是10000*10,而代碼二中由於是使用了鎖,從而保證了同一個時間只能有一個線程修改count的值,所以最終結果是10000*10.

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.