Python threading多線程編程執行個體

來源:互聯網
上載者:User
Python 的多線程有兩種實現方法:

函數,線程類

1.函數

調用 thread 模組中的 start_new_thread() 函數來建立線程,以線程函數的形式告訴線程該做什麼

複製代碼 代碼如下:


# -*- coding: utf-8 -*-
import thread
def f(name):
#定義線程函數
print "this is " + name

if __name__ == '__main__':
thread.start_new_thread(f, ("thread1",))
#用start_new_thread()調用線程函數和其他參數
while 1:
pass

不過這種方法暫時沒能找到其他輔助方法,連主線程等待都要用 while 1 這種方法解決。

2.線程類

調用 threading 模組,建立 threading.Thread 的子類來得到自訂線程類。
複製代碼 代碼如下:


# -*- coding: utf-8 -*-
import threading
class Th(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.t_name = name
#調用父類建構函式

def run(self):
#重寫run()函數,線程預設從此函數開始執行
print "This is " + self.t_name

if __name__ == '__main__':
thread1 = Th("Thread_1")
thread1.start()
#start()函數啟動線程,自動執行run()函數

threading.Thread 類的可繼承函數:
getName() 獲得線程對象名稱
setName() 設定線程對象名稱
join() 等待調用的線程結束後再運行之後的命令
setDaemon(bool) 阻塞模式, True: 父線程不等待子線程結束, False 等待,預設為 False
isDaemon() 判斷子線程是否和父線程一起結束,即 setDaemon() 設定的值
isAlive() 判斷線程是否在運行

執行個體

複製代碼 代碼如下:


import threading
import time
class Th(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.setName(thread_name)

def run(self):
print "This is thread " + self.getName()
for i in range(5):
time.sleep(1)
print str(i)
print self.getName() + "is over"

join() 阻塞等待

複製代碼 代碼如下:


if __name__ == '__main__':
thread1 = Th("T1 ")
thread1.start()
#thread1.join()
print "main thread is over"

不帶 thread1.join() ,得到如下結果:
複製代碼 代碼如下:


This is thread T1
main thread is over
0
1
2
T1 is over


不等待 thread1 完成,執行之後語句。
加了 thread1.join() ,得到如下結果:
複製代碼 代碼如下:


This is thread T1
0
1
2
T1 is over
main thread is over


阻塞等待 thread1 結束,才執行下面語句

主線程等待

複製代碼 代碼如下:


if __name__ == '__main__':
thread1 = Th("T1 ")
thread1.setDaemon(True)
#要線上程執行之前就設定這個量
thread1.start()
print "main thread is over"

報錯: Exception in thread T1 (most likely raised during interpreter shutdown):
也就是主線程不等待子線程就結束了。

多個子線程
複製代碼 代碼如下:


if __name__ == '__main__':
for i in range(3):
t = Th(str(i))
t.start()
print "main thread is over"

這裡的 t 可同時處理多個線程,即 t 為線程控制代碼,重新賦值不影響線程。

這裡奇怪的是,運行 t.run() 時,不會再執行其他線程。雖不明,還是用 start() 吧。暫且理解為 start() 是非阻塞並行的,而 run 是阻塞的。

線程鎖

threading 提供線程鎖,可以實現線程同步。
複製代碼 代碼如下:


import threading
import time
class Th(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.setName(thread_name)

def run(self):
threadLock.acquire()
#獲得鎖之後再運行
print "This is thread " + self.getName()
for i in range(3):
time.sleep(1)
print str(i)
print self.getName() + " is over"
threadLock.release()
#釋放鎖
if __name__ == '__main__':
threadLock = threading.Lock()
#設定全域鎖
thread1 = Th('Thread_1')
thread2 = Th('Thread_2')
thread1.start()
thread2.start()

得到結果:
複製代碼 代碼如下:


This is thread Thread_1
0
1
2
Thread_1 is over
This is thread Thread_2
0
1
2
Thread_2 is over
  • 聯繫我們

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