python 多線程 start_new_thread()

來源:互聯網
上載者:User

標籤:python   多線程   

一、簡述

  CPython實現細節: 由於GIL(Global Interpreter Lock),在CPython中一次只能有一個線程來執行python代碼,不過有些面向執行的庫可以克服這個限制。如果想要使你的應用程式更好的利用電腦資源的話,最好使用multiprocessing。 但是,如果同時運行多個I/O任務的話,線程依然是一個很好地選擇。
  python線程的作用主要是應對I/O任務,例如網路資料的讀寫等。

二、樣本

  1. 函數說明。
  start_new_thread ( function , args [ , kwargs ] )
  建立一個新的線程,返回一個線程標識符。function是線程函數,args是線程函數的參數,是一個list。kwargs選擇性參數,可不填。

#!/usr/bin/env python# _*_ coding = utf-8 _*_import threadimport timedef work_thread(id):    cnt = 1    print "Thread %d is runing..." % id    while True:        print "Thread with ID %d has counter value %d" % (id, cnt)        time.sleep(2)         cnt += 1for i in range(1,5):    thread.start_new_thread(work_thread,(i,))print "Main thread doing an infinite wait loop..."while True:    pass

運行代碼,輸出結果如下:

$ ./thread_demo.py
Main thread doing an infinite wait loop…
Thread 3 is runing…
Thread 1 is runing…
Thread 2 is runing…
Thread 4 is runing…
Thread with ID 1 has counter value 1
Thread with ID 4 has counter value 1
Thread with ID 2 has counter value 1
Thread with ID 3 has counter value 1
Thread with ID 2 has counter value 2
Thread with ID 3 has counter value 2
Thread with ID 4 has counter value 2
Thread with ID 1 has counter value 2
Thread with ID 3 has counter value 3
Thread with ID 4 has counter value 3
Thread with ID 1 has counter value 3
Thread with ID 2 has counter value 3
Thread with ID 1 has counter value 4
Thread with ID 4 has counter value 4
Thread with ID 2 has counter value 4
Thread with ID 3 has counter value 4

線程退出函數:
thread.exit ()。結束當前線程。調用該函數會觸發 SystemExit 異常,如果沒有處理該異常,線程將結束。

python 多線程 start_new_thread()

相關文章

聯繫我們

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