什么是進程?
進程是二進制可執(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()
``
運行結果如圖:
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()
``
運行結果如圖: