歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python多線程編程

Python多線程編程

日期:2017/3/1 9:26:25   编辑:Linux編程

python2.4前有個thread模塊支持多線程編程,2.4後新增了threading模塊,提供更高級別和更強大的線程支持.

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

除此之外,threading提供了很多和java中Thread類一樣的方法:(注意這是都是實例方法)

  • run(): The run() method is the entry point for a thread.
  • start(): The start() method starts a thread by calling the run method.
  • join([time]): The join() waits for threads to terminate.
  • isAlive(): The isAlive() method checks whether a thread is still executing.
  • getName(): The getName() method returns the name of a thread.
  • setName(): The setName() method sets the name of a thread.

創建線程的方式有兩種:

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()

下面關於Python的文章您也可能喜歡,不妨看看:

Python:在指定目錄下查找滿足條件的文件 http://www.linuxidc.com/Linux/2015-08/121283.htm

Python2.7.7源碼分析 http://www.linuxidc.com/Linux/2015-08/121168.htm

無需操作系統直接運行 Python 代碼 http://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved