Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python 多線程編程入門:threading 模塊详解

Python 2.4 之前有 thread 模塊支持多線程編程,2.4 之後新增了 threading 模塊,提供了更高級、更強大的線程支持。

threading 提供了一些模塊級函數:

  • threading.activeCount():返回激活的線程對象數量
  • threading.currentThread():返回當前正在執行的線程對象
  • threading.enumerate():返回當前激活的線程對象列表

此外,threading 還提供了許多與 Java 中 Thread 類相似的方法(注意:以下都是實例方法):

  • run():線程的入口方法
  • start():通過調用 run 來啟動線程
  • join([time]):等待線程終止
  • isAlive():檢查線程是否仍在執行
  • getName():返回線程名稱
  • setName():設置線程名稱

創建線程有兩種方式:

1)繼承 threading.Thread

a. 創建一個 threading.Thread 的子類;
b. 覆蓋 init(self [,args]);
c. 重寫 run 方法。

#!/usr/bin/python
#!coding=utf-8
import threading
import time
exitFlag = 0
class MyThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        task()
    def task(self):
        '''線程要執行的任務'''
        print 'starting ' + self.name
        print 'exiting ' + self.name
# 創建線程
thread1 = MyThread(1, 'Thread-1', 1)
thread2 = MyThread(2, 'Thread-2', 2)
# 啟動線程
thread1.start()
thread2.start()
# 等待線程結束
thread1.join()
thread2.join()
print 'exiting main thread'

2)把任務函數作為參數傳給 Thread

threading.Thread(target=task, args=()).start()

這種方式更為簡潔,直接把要執行的函數與參數傳入即可,適合任務邏輯簡單的場景。

Copyright © Linux教程網 All Rights Reserved