Python 創建線程

       關於 線程 是什麼東東 就不介紹了,直接進入正題。

       Python 有多個模塊可以支持多線程,thread,threading,Queue。此處不提Queue,有興趣自己瞭解

       thread模塊提供了基本的線程和鎖得支持,threading 提供了更全面的更高級的線程支持。因此除非特別需要,否則請使用threading而不是thread。

       Python創建線程一般來說有三種方式:

                       1.創建一個Thread對象,傳入一個函數

                       2.創建一個Thread對象,傳入一個可調用的類對象

                       3.創建一個類對象,該對象繼承自Thread

       至於如何創建線程,請看個人愛好與需求

第一種方式:   創建一個Thread對象,傳入一個函數

import threading
from time import ctime,sleep


def func(thread):
    print 'i am thread',thread,'nothing else'
    sleep(5)    
    print 'thread',thread,'is over'


def main():
    t1 = threading.Thread(target = func,args = (1,))
    sleep(2)
    t2 = threading.Thread(target = func,args = (1,))
    t1.start()   
    t2.start()
    t1.join()    
    t2.join()
    
    
if __name__ == '__main__':
    main()

Thread 的 args 參數要求 必須返回一個迭代器,因此 把   (1,) 改爲  1 是不可以的 ,會報錯。如下


start() 開始線程

join()  等待線程結束

第二種方式:創建一個Thread對象,傳入一個可調用的類對象

import threading
from time  import ctime,sleep


class Mythread (object) :
    def __init__(self,func,args):
        self.func = func
        self.args = args
    def __call__(self):
        self.func(self.args)


def func(thread):
    print 'i am thread',thread,'nothing else'
    sleep(5)
    print 'thread',thread,'is over'


def main():
    t1 = threading.Thread(target=Mythread(func,1))
    t2 = threading.Thread(target=Mythread(func,2))
    t1.start()
    sleep(2)
    t2.start()
    t1.join()
    t2.join()
    
    
if __name__ == '__main__':
    main()



第三種方式:創建一個類對象,該對象繼承自Thread

import threading
from time  import ctime,sleep


class MyThread(threading.Thread):
    def __init__(self,func,args):
        threading.Thread.__init__(self)
        self.func = func
        self.args = args
    def run(self):
        self.func(self.args)


def func(thread):
    print 'i am thread',thread,'nothing else'
    sleep(5)
    print 'thread',thread,'is over'


def main():
    t1 = MyThread(func,1)
    t2 = MyThread(func,2)
    t1.start()
    sleep(2)
    t2.start()
    t1.join()
    t2.join()


if __name__ == '__main__':
    main()


更多線程方面細節知識,請查閱Python 核心編程。

本人初學者。如何任何不當之處,歡迎指正,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章