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

Python多線程threading

日期:2017/3/1 9:14:50   编辑:Linux編程

本文通過 4個example 介紹python中多線程package —— threading的常用用法, 包括調用多線程, 同步隊列類Queue, Ctrl+c結束多線程。

example1.

調用10個線程, 分別打印0~4, 每打印一個數pause一秒鐘。

code如下所示, 在test()函數中用threading.Thread建立10個線程;
一種方法是不要將這些線程設置為守護線程,如code所示;
一種方法是設置守護線程( setDeamon(True)),並用join()讓程序等所有線程結束了再退出(即去掉code中的注釋);


#/*********************************************************************
# *-
# * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
# *-
# *********************************************************************
#-
#-
#-
#/**
# * @file b.py
# * @author zhangruiqing01([email protected])
# * @date 2015/10/28 20:12:33
# * @brief-
# *--
# **/
#

import time
import threading

def printf(i):
    for x in xrange(5):
        time.sleep(1)
        print i,

def test():
    thread_list = []
    for i in xrange(10):
        sthread = threading.Thread(target = printf, args = str(i))
#        sthread.setDaemon(True)
        sthread.start()
        thread_list.append(sthread)
#    for i in xrange(10):
#        thread_list[i].join()


if __name__ == '__main__':
    test()

結果:

$python b.py
0 1 2 3 4 5 6 7 8 9 2 1 0 4 5 6 7 3 8 9 1 2 0 5 6 7 4 3 8 9 2 1 0 6 7 4 3 5 8 9 1 0 2 7 4 635 8 9




example2.

調用10個守護線程(每個守護線程的timeout時間為1s), 分別打印0~4, 每打印一個數pause x秒鐘, x為0~4之間的randint值。



#/***************************************************************************
# *-
# * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
# *-
# **************************************************************************/
#-
#-
#-
#/**
# * @file c.py
# * @author zhangruiqing01([email protected])
# * @date 2015/10/28 20:15:33
# * @brief-
# *--
# **/
#

import time
import threading
import random

def printf(i):
    randtime = random.randint(1,5)
    for x in xrange(5):
        time.sleep(randtime)
        print "T" + str(i), randtime # print T<threadid> randtime

def test():
    thread_list = []
    for i in xrange(10):
        sthread = threading.Thread(target = printf, args = str(i))
        sthread.setDaemon(True)
        sthread.start()
        thread_list.append(sthread)
    for i in xrange(10):
        thread_list[i].join(1)


if __name__ == '__main__':
    test()

結果:


從圖中可見,在運行的這10s中, pause x秒的thread被打印了[10/x]次。

example3.

引入Queue, 帶同步功能(enqueue和dequeue不用手動加鎖)的queue類。

在下面的code中,proc函數處理一個thread的操作:
1. dequeue 一個隊頭元素
2. enqueue 5個threadid
3. 重復執行兩次步驟2(epoch<2)

這裡注意proc函數中的最後Q.task_done()表示一個任務(一個dequeue的元素)已經結束;test( )中最後的Q.join()為等待隊列為空才退出程序。

#/***************************************************************************
# *-
# * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
# *-
# **************************************************************************/
#-
#-
#-
#/**
# * @file d.py
# * @author zhangruiqing01([email protected])
# * @date 2015/10/28 20:22:33
# * @brief-
# *--
# **/
#

import time
import threading
import random
import Queue

Q = Queue.Queue()

def proc(threadid, epoch):
    while True:
        time.sleep(1)
        try:
            ele = Q.get()
            print 'Thread ' + str(threadid) + ' get element ' + str(ele)
        except Queue.Empty:
            print 'Thread ' + str(threadid) + ' get empty queue'
            continue
        if int(epoch) < 2:
            for i in xrange(5):
                Q.put(threadid)
            epoch = int(epoch) + 1

        Q.task_done()


def test():
    Q.put(1)
    thread_list = []
    for i in xrange(3):
        args = [str(i), str(0)]
        sthread = threading.Thread(target = proc, args = args)
        sthread.setDaemon(True)
        sthread.start()
        thread_list.append(sthread)
    Q.join()


if __name__ == '__main__':
    test()

結果:

PS:最開始get到的1是在test()中put進去的;





example4.

程序接收ctrl + c後退出。程序每個thread打印100次threadid,直到ctrl+c退出。

PS: 更好的設計是在try,except後加finally塊, 做到即便不ctrl+c也可以正常退出,就留給大家下面練習吧~

#/***************************************************************************
# *-
# * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
# *-
# **************************************************************************/
#-
#-
#-
#/**
# * @file a.py
# * @author zhangruiqing01([email protected])
# * @date 2015/10/28 20:06:33
# * @brief-
# *--
# **/
#

import time
import threading

def printf(i):
    for x in xrange(100):
        time.sleep(1)
        print i,

def test():
    for i in xrange(10):
        sthread = threading.Thread(target = printf, args = str(i))
        sthread.setDaemon(True)
        sthread.start()
    try:
        while 1:
            time.sleep(1)
    except KeyboardInterrupt:
        print 'exit'



if __name__ == '__main__':
    test()

運行結果:


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