python 多執行緒 入門

bitcarmanlee發表於2016-06-03

python裡的多執行緒,一直用得不是很多。為了最快速的上手,搞明白多執行緒到底是個什麼鬼,寫了個簡單的例子

#!/usr/bin/env python
#coding:utf-8

'''
Created on 2016年6月3日

@author: lei.wang
'''

import threading
from time import ctime,sleep

def music(entertainment):
    for i in range(2):
        print "Listening to %s. %s" %(entertainment,ctime())
        sleep(1)


def movie(entertainment):
    for i in range(2):
        print "Watching the %s. %s" %(entertainment,ctime())
        sleep(5)



if __name__ == '__main__':
    threads = []
    thread_music = threading.Thread(target=music,args=(u"暗號",))
    threads.append(thread_music)
    thread_movie = threading.Thread(target=movie,args=(u"肖聖克救贖",))
    threads.append(thread_movie)

    for each in threads:
        each.setDaemon(True)
        each.start()

    each.join()

    print "all threads end at %s" %(ctime())    

程式碼執行結果

Listening to 暗號. Fri Jun  3 12:38:12 2016
Watching the 肖聖克救贖. Fri Jun  3 12:38:12 2016
Listening to 暗號. Fri Jun  3 12:38:13 2016
Watching the 肖聖克救贖. Fri Jun  3 12:38:17 2016
all threads end at Fri Jun  3 12:38:22 2016

對程式碼做個簡單的分析:
首先建立一個空的threads列表,用來存放執行緒。然後分別建立執行緒thread_music與thread_moive。

將Thread中原始碼建構函式的說明部分摳出來:

class Thread(_Verbose):
    """A class that represents a thread of control.

    This class can be safely subclassed in a limited fashion.

    """
    __initialized = False
    # Need to store a reference to sys.exc_info for printing
    # out exceptions when a thread tries to use a global var. during interp.
    # shutdown and thus raises an exception about trying to perform some
    # operation on/with a NoneType
    __exc_info = _sys.exc_info
    # Keep sys.exc_clear too to clear the exception just before
    # allowing .join() to return.
    __exc_clear = _sys.exc_clear

    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, verbose=None):
        """This constructor should always be called with keyword arguments. Arguments are:

        *group* should be None; reserved for future extension when a ThreadGroup
        class is implemented.

        *target* is the callable object to be invoked by the run()
        method. Defaults to None, meaning nothing is called.

        *name* is the thread name. By default, a unique name is constructed of
        the form "Thread-N" where N is a small decimal number.

        *args* is the argument tuple for the target invocation. Defaults to ().

        *kwargs* is a dictionary of keyword arguments for the target
        invocation. Defaults to {}.

        If a subclass overrides the constructor, it must make sure to invoke
        the base class constructor (Thread.__init__()) before doing anything
        else to the thread.

"""

通過原始碼,很容易看出來
thread_music = threading.Thread(target=music,args=(u"暗號",))
是如何構造一個執行緒的。

jion()方法放在for迴圈外邊,就是說必須要等for迴圈裡的兩個程式都結束以後,才能繼續執行主程式。

從程式碼最後的結果來分析,thread_music與thread_movie是同時開始執行的,music程式sleep1s後執行第二次,而movie程式sleep5s後執行第二次。主程式在兩個執行緒都執行完了以後才執行。

相關文章