python 實現(xiàn)多線程編程

什么是進程?

進程是二進制可執(zhí)行文件的數(shù)據(jù),他們只有被調(diào)到內(nèi)存中,被操作系統(tǒng)調(diào)用的時候才開始他們的生命周期,進程是程序的每一次執(zhí)行,進程有單獨的內(nèi)存空間、數(shù)據(jù)棧等,所以只能使用進程間通信(IPC),而不能直接共享信息。

什么是線程?

線程又稱輕量級進程,所有線程運行在同一進程中,共享相同的運行環(huán)境。一個進程中各線程的數(shù)據(jù)是共享的。
在python中使用thread模塊實現(xiàn)多讀線程操作。
倒入thread模塊import thread
如果沒有使用線程,系統(tǒng)執(zhí)行任務是順序的,一個執(zhí)行完后才會去執(zhí)行另一個,我們通過sleep函數(shù)驗證cpu等待任務過程。
示例代碼如下:
`` #!/usr/bin/env python
from time import sleep, ctime

def loop0():
print 'start loop0 at:', ctime()
sleep(4)
print 'loop0 done at:', ctime()

def loop1():
print 'start loop1 at:',ctime()
sleep(2)
print 'loop1 done at:', ctime()

def main():
print 'string at :', ctime()
loop0()
loop1()
print 'all done at:', ctime()

if name == 'main':
main()
``
運行結果如圖:

image.png

python的threading模塊

python提供了幾個線程模塊,包括thread、threading、queue等。thread和threading允許程序員創(chuàng)建和管理線程,thread提供基本線程和鎖支持,threading提供更高級的線程管理。queue允許用戶創(chuàng)建一個可以用于多個線程之間個共享數(shù)據(jù)的數(shù)據(jù)結構。
使用thread創(chuàng)建線程示例代碼如下:
``

!/usr/bin/env python

import thread
from time import ctime, sleep

def loop0():
print 'start loop 0 at:', ctime()
sleep(4)
print 'loop 0 done at:', ctime()

def loop1():
print 'start loop 1 at:', ctime()
sleep(2)
print 'loop 1 done at:', ctime()

def main():
print 'starting at:', ctime()
thread.start_new_thread(loop0,())
thread.start_new_thread(loop1,())
sleep(6)
print 'all done at:', ctime()

if name == 'main':
main()
``
運行結果如圖:

image.png
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • 線程 引言&動機 考慮一下這個場景,我們有10000條數(shù)據(jù)需要處理,處理每條數(shù)據(jù)需要花費1秒,但讀取數(shù)據(jù)只需要0....
    不浪漫的浪漫_ea03閱讀 374評論 0 0
  • 引言&動機 考慮一下這個場景,我們有10000條數(shù)據(jù)需要處理,處理每條數(shù)據(jù)需要花費1秒,但讀取數(shù)據(jù)只需要0.1秒,...
    chen_000閱讀 527評論 0 0
  • 概述 多線程給我們帶來的好處是可以并發(fā)的執(zhí)行多個任務,特別是對于I/O密集型的業(yè)務,使用多線程,可以帶來成倍的性能...
    SimonChen閱讀 9,549評論 0 5
  • 我們前面提到了進程是由若干線程組成的,一個進程至少有一個線程。多線程優(yōu)點: 在一個進程中的多線程和主線程分享相同的...
    第八共同體閱讀 529評論 0 0
  • 多線程模塊 threading 創(chuàng)建多線程的兩種方式:import threadingimport time 創(chuàng)建...
    錢塘閱讀 400評論 0 3