Python之線程(一)

一 線程的啓動與停止

線程需要使用線程庫threading。

from threading import Thread
import time

################直接調用的方式創建線程################
#
定義多線程要運行函數
def countdown(num):
    while num > 0:
        print("T-Minus",num)
        num -= 1
       
time.sleep(1)

t = Thread(target=countdown,args=(10,))

t.start()

##################繼承的方式創建線程##################
class MyThread(Thread):
    def __init__(self,num):
        #Thread.__init__(self)
       
super
(MyThread,self).__init__()
        self.num = num
   
def run(self):
        while self.num > 0:
            print("self.num=>", self.num)
            self.num -= 1
           
time.sleep(1)

t = MyThread(10)
t.run()

 

二 守護線程 和 前臺線程

什麼是守護線程?

就是在後臺默默執行的線程,比如Java的GC就是一守護線程

當主線程結束的時候,無論守護線程是否運行完畢,是否成功,守護線程子線程都會立即結束

 

什麼是非守護線程?
當主線程結束的時候,必須等待其他這些非守護線程運行結束才能結束

 

非守護線程的例子:

from threading import Thread
import time

def show(name):
    for i inrange(5):
        time.sleep(0.5)
        print("%s --> %s" %(name,i))


if __name__ == '__main__':
    t =Thread(target=show,args=("守護線程",))
    #非守護線程:主線程必須等非守護線程全部結束才能結束
   
t.start()
    time.sleep(2)
    print("main thread ending")

結果:

守護線程 --> 0

守護線程 --> 1

守護線程 --> 2

main thread ending

守護線程 --> 3

守護線程 --> 4

 

from threading import Thread
import time

def show(name):
    for i inrange(5):
        time.sleep(0.5)
        print("%s --> %s" %(name,i))


if __name__ == '__main__':
    t =Thread(target=show,args=("守護線程",))
    #守護線程:主線程結束,守護線程也必須結束掉
   
t.setDaemon(True)
    t.start()
    time.sleep(2)
    print("main thread ending")

結果:

守護線程 --> 0

守護線程 --> 1

守護線程 --> 2

main thread ending

 

三  多線程的JOIN

我們知道在java中,Thread有一靜態方法,join,表示一個線程B加入線程A的尾部,在A執行完畢之前,B不能執行;而且還帶有timeout參數,表示超過某個時間則停止等待,變爲可運行狀態,等待CPU的調度

3.1 非守護線程

Python中,默認情況下,如果不加join語句,那麼主線程不會等到當前線程結束才結束,但卻不會立即殺死該線程

from threading import Thread
import time

class ShowThread(Thread):
    def __init__(self,name):
        super(ShowThread,self).__init__()
        self.name = name
   
def run(self):
        for i inrange(5):
            time.sleep(0.5)
            print("[%s] --> %s" % (self.name, i))

def present():
    for i inrange(5):
        print("[present] --> %s" %(i))


if __name__ == '__main__':
    A =ShowThread("show")
    A.start()
    present()

[present] --> 0

[present] --> 1

[present] --> 2

[present] --> 3

[present] --> 4

[show] --> 0

[show] --> 1

[show] --> 2

[show] --> 3

[show] --> 4

 

如果加上join,則會阻塞當前線程,其他線程包括主線程,都必須等待該線程運行完畢,才能繼續運行

 

if __name__ == '__main__':
    A =ShowThread("show")
    A.start()
    A.join()
    present()

結果:

[show] --> 0

[show] --> 1

[show] --> 2

[show] --> 3

[show] --> 4

[present] --> 0

[present] --> 1

[present] --> 2

[present] --> 3

[present] --> 4

 

我們也可以指定阻塞多長時間,如果超過這個時間,那麼其他線程不再繼續等待,可以被CPU調度了

if __name__ == '__main__':
    A =ShowThread("show")
    A.start()
    A.join(2)
    present()

結果:

[show] --> 0

[show] --> 1

[show] --> 2

[show] --> 3

[present] --> 0

[present] --> 1

[present] --> 2

[present] --> 3

[present] --> 4

[show] --> 4

 

3.2 守護線程

對於守護線程,如果我們沒有使用join,那麼主線程運行完畢之後,守護線程無論是否運行完畢,都結束了

if __name__ == '__main__':
    A =ShowThread("show")
    A.setDaemon(True)
    A.start()
    time.sleep(0.5)
    present()

結果:

[show] --> 0

[present] --> 0

[present] --> 1

[present] --> 2

[present] --> 3

[present] --> 4

 

對於守護線程,如果使用join,那麼守護線程就會阻塞主線程,主線程需要等待守護線程運行結束才能運行

if __name__ == '__main__':
    A =ShowThread("show")
    A.setDaemon(True)
    A.start()
    time.sleep(0.5)
    A.join()
    present()

結果:

[show] --> 0

[show] --> 1

[show] --> 2

[show] --> 3

[show] --> 4

[present] --> 0

[present] --> 1

[present] --> 2

[present] --> 3

[present] --> 4

 

我們對join指定阻塞時間,如果超過這個時間,那麼守護線程就不再阻塞主線程,主線程就可以繼續運行,運行結束,無論守護線程是否運行完畢,都給結束掉

if __name__ == '__main__':
    A =ShowThread("show")
    A.setDaemon(True)
    A.start()
    A.join(timeout=1)
    present()

結果:

[show] --> 0

[show] --> 1

[present] --> 0

[present] --> 1

[present] --> 2

[present] --> 3

[present] --> 4

 

四 線程鎖

一個進程下可以啓動多個線程,多個線程共享父進程的內存空間,也就意味着每個線程可以訪問同一份數據,此時,如果2個線程同時要修改同一份數據,會出現什麼狀況?


當一個線程調用鎖的acquire()方法獲得鎖時,鎖就進入“locked”狀態。每次只有一個線程可以獲得鎖。如果此時另一個線程試圖獲得這個鎖,該線程就會變爲“blocked”狀態,稱爲同步阻塞(參見多線程的基本概念)。
直到擁有鎖的線程調用鎖的release()方法釋放鎖之後,鎖進入“unlocked”狀態。線程調度程序從處於同步阻塞狀態的線程中選擇一個來獲得鎖,並使得該線程進入運行(running)狀態。


from threading import Thread
from threading import Lock
import time

class Ticket(object):
    def __init__(self,tickets):
        self.tickets = tickets
   
def sell(self):
        self.tickets -= 1

class TicketSeller(Thread):
    def __init__(self,ticket):
        super(TicketSeller,self).__init__()
        self.ticket = ticket
       
self.lock = Lock()
    def run(self):
        for i inrange(5):
            time.sleep(1)
            self.lock.acquire()
            self.ticket.sell()
            self.lock.release()
            print("%s ===%s" %(self.getName(),ticket.tickets))
if __name__ == '__main__':
    ticket = Ticket(500)

    sellerList = []
    for i in range(5):
        seller = TicketSeller(ticket)
        seller.start()
        sellerList.append(seller)
    for seller in sellerList:
        seller.join()

    print("剩餘票數:%s" %(ticket.tickets))

五 遞歸鎖與信號量

5.1  什麼是信號量

我們先看一下Java中的實現,Semaphore=>

Semaphore是用來保護一個或者多個共享資源的訪問,Semaphore內部維護了一個計數器,其值爲可以訪問的共享資源的個數。一個線程要訪問共享資源,先獲得信號量,如果信號量的計數器值大於1,意味着有共享資源可以訪問,則使其計數器值減去1,再訪問共享資源。
如果計數器值爲0,線程進入休眠。當某個線程使用完共享資源後,釋放信號量,並將信號量內部的計數器加1,之前進入休眠的線程將被喚醒並再次試圖獲得信號量。
就好比一個廁所管理員,站在門口,只有廁所有空位,就開門允許與空側數量等量的人進入廁所。多個人進入廁所後,相當於N個人來分配使用N個空位。爲避免多個人來同時競爭同一個側衛,在內部仍然使用鎖來控制資源的同步訪問

 

import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;

public class ResourceManager {
    /** 可重入鎖,對資源列表進行同步 */
   
private final ReentrantLock lock = new ReentrantLock();
    /** 可使用的資源列表 */
   
private final LinkedList<Object> resourceList = new LinkedList<Object>();
    /** 信號量 */
   
private Semaphore semaphore ;

    publicResourceManager(Collection<Object> resourceList) {
        this.resourceList.addAll(resourceList);
        this.semaphore = new Semaphore(resourceList.size(), true);
    }

    /**獲取資源*/
   
public Object acquire() throws InterruptedException {
        semaphore.acquire();
        Object resource = null;
        lock.lock();
        try {
            resource = resourceList.poll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return resource;
    }
    /**釋放或則歸還資源*/
   
public void release(Object resource){
        lock.lock();
        try {
            resourceList.addLast(resource);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        semaphore.release();
    }
}

 

public class Consumer implements Runnable{

    private ResourceManager rm;

    publicConsumer() {
    }

    publicConsumer(ResourceManager rm) {
        this.rm = rm;
    }
    @Override
   
public void run() {
        Object resource = null;
        try {
            resource = rm.acquire();
            System.out.println(Thread.currentThread().getName()+" work on " + resource);
            /*resource做工作*/
           
Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName() + " finish on " + resource);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            /*歸還資源*/
           
if (resource != null) {
                rm.release(resource);
            }
        }
    }

    public ResourceManager getRm() {
        return rm;
    }

    public void setRm(ResourceManager rm) {
        this.rm = rm;
    }
}

 

public class SignalClient {
    public staticvoid main(String[] args) {
        /*準備2個可用資源*/
       
List<Object> resourceList = new ArrayList<Object>();
        resourceList.add("Resource1");
        resourceList.add("Resource2");

        /*準備工作任務*/
       
final ResourceManager rm = new ResourceManager(resourceList);
        Consumer consumer = new Consumer(rm);
        /*啓動10個任務*/
       
ExecutorServiceservice = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            service.submit(consumer);
        }
        service.shutdown();
    }
}

python中的實現

from threading import Thread
from threading import Lock
from threading import Semaphore
from queue import Queue
import time

'''負責資源的存放,以及維護Semaphore的狀態'''
class ResouceManager(object):
    def __init__(self,resourceList):
        self.resourceList = resourceList
       
self.lock = Lock()
        self.sem = Semaphore(value=len(resourceList))

    '''獲取資源'''
   
def acquire(self):
        self.sem.acquire()#內部計數器減1
       
self.lock.acquire()
        resource = self.resourceList.pop()
        self.lock.release()
        return resource
    '''釋放資源'''
   
def release(self,resource):
        self.lock.acquire()
        self.resourceList.append(resource)
        self.lock.release()
        self.sem.release()#內部計數器加1

class Consumer(Thread):
    def __init__(self,rm):
        super(Consumer, self).__init__()
        self.rm = rm

   
def run(self):
        resource = self.rm.acquire()
        print("%s work onthe resource: %s" %(self.getName(),resource))
        time.sleep(3)
        self.rm.release(resource)

if __name__ == "__main__":
    '''構建資源'''
   
resourceList = ["resource1","resource2"]
    rm =ResouceManager(resourceList)

    for i in range(10):
        consumer = Consumer(rm)
        consumer.start()

 

5.2RLock遞歸鎖或者叫做可重入鎖

它與Lock的區別在於,RLock允許在一個線程被多次acquire,但是Lock卻不允許這種情況,acquire和release必須成對出現。

from threading import RLock
import time

lock = RLock()
def run1():
    print("grab the first part data")
    lock.acquire()
    global num
    num += 1
   
lock.release()
    return num


def run2():
    print("grab the second part data")
    lock.acquire()
    global num2
    num2 += 1
   
lock.release()
    return num2


def run3():
    lock.acquire()
    res = run1()
    print('--------between run1 and run2-----')
    res2 = run2()
    lock.release()
    print(res, res2)

 

六Condition

from threading import Thread,Condition
import time
'''
所謂條件變量,即這種機制是在滿足了特定的條件後,線程纔可以訪問相關的數據
'''

class Goods(object):
    def __init__(self):
        self.count = 0

   
def add(self, num=1):
        self.count += num

   
def sub(self):
        if self.count>=0:
            self.count -= 1

   
def isEmpty(self):
        return self.count <= 0
class Producer(Thread):
    def __init__(self, condition, goods, sleeptime = 1):
        super(Producer,self).__init__()
        self.condition = condition
       
self.goods = goods
       
self.sleeptime = sleeptime

   
def run(self):
        condition = self.condition
        goods = self.goods
        while True:
            condition.acquire()  # 鎖住資源
           
goods.add()
            print("產品數量:", goods.count, "生產者線程")
            condition.notifyAll()  # 喚醒所有等待的線程--》其實就是喚醒消費者進程
           
condition.release()  # 解鎖資源
           
time.sleep(self.sleeptime)

class Consumer(Thread):#消費者類
   
def __init__(self,condition,goods,sleeptime = 2):#sleeptime=2
       
super
(Consumer, self).__init__()
        self.condition = condition
       
self.goods = goods
       
self.sleeptime = sleeptime
   
def run(self):
        condition = self.condition
        goods = self.goods
        while True:
            time.sleep(self.sleeptime)
            condition.acquire()#鎖住資源
           
while goods.isEmpty():#如無產品則讓線程等待
               
condition.wait()
            goods.sub()
            print("產品數量:",goods.count,"消費者線程")
            condition.release()#解鎖資源

if __name__ == "__main__":
    g =Goods()
    c = Condition()

    pro = Producer(c, g)
    pro.start()

    con = Consumer(c, g)
    con.start()

 

七 同步隊列

from threading import Thread,Condition
import time
from queue import Queue

class Worker(Thread):
    def __init__(self,index,queue):
        super(Worker, self).__init__()
        self.index = index
       
self.queue = queue

   
def run(self):
        while True:
            time.sleep(1)
            item = self.queue.get()
            if item is None:
                break
            print("序號:", self.index, "任務", item, "完成")
            # task_done方法使得未完成的任務數量-1
           
self.queue.task_done()

if __name__ == "__main__":
    '''
       
初始化函數接受一個數字來作爲該隊列的容量,如果傳遞的是
       
一個小於等於0的數,那麼默認會認爲該隊列的容量是無限的.
    '''
   
queue = Queue(0)
    for i inrange(10):
        queue.put(i)  # put方法使得未完成的任務數量+1

   
for i in range(2):
        Worker(i, queue).start()  # 兩個線程同時完成任務

 

八 多進程

多任務可以由多進程完成,也可以由一個進程內的多線程完成。

Multiprocessing模塊用於跨平臺多進程模塊,提供一個Process類代表一個進程對象

創建子進程時,只需要傳入一個執行函數和函數的參數,創建一個Process實例,用start()方法啓動,這樣創建進程比fork()還要簡單。
join()方法可以等待子進程結束後再繼續往下運行,通常用於進程間的同步。

 

from multiprocessing import Process
import time


def f(name):
    time.sleep(2)
    print('hello', name)


if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

from multiprocessing import Process
import time

def info(title):
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())
    print("\n\n")


def f(name):
    info('\033[31;1mfunction f\033[0m')
    print('hello', name)


if __name__ == '__main__':
    info('\033[32;1mmain process line\033[0m')
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

 

九 進程間通訊

Process之間肯定是需要通信的,操作系統提供了很多機制來實現進程間的通信。Python的multiprocessing模塊包裝了底層的機制,提供了Queue、Pipes等多種方式來交換數據。
我們以Queue爲例,在父進程中創建兩個子進程,一個往Queue裏寫數據,一個從Queue裏讀數據:
from multiprocessing import Process, Queue
import os, time, random

# 寫數據進程執行的代碼:
def write(q):
    print("process to write: %s" %os.getpid())
    for value in range(5):
        print("Put [%s] to queue: " %value)
        q.put(value)
        time.sleep(random.random())

def read(q):
    print("process to read: %s" % os.getpid())
    while True:
        value = q.get(True)
        print('Get [%s] from queue.' % value)

if __name__ == "__main__":
    # 父進程創建Queue,並傳給各個子進程:
    q = Queue()
    pw = Process(target=write,args=(q,))
    pr = Process(target=read, args=(q,))
    # 啓動子進程pw,寫入:
    pw.start()
    # 等待pw結束:
    pw.join()
    # 啓動子進程pr,讀取:
    pr.start()

    # pr進程裏是死循環,無法等待其結束,只能強行終止:
    #pr.terminate()

 

九 進程池

如果要啓動大量的子進程,可以用進程池的方式批量創建子進程:
Pool對象調用join()方法會等待所有子進程執行完畢,調用join()之前必須先調用close(),調用close()之後就不能繼續添加新的Process了。
請注意輸出的結果,task 0123是立刻執行的,而task 4要等待前面某個task完成後才執行,這是因爲Pool的默認大小在我的電腦上是4,因此,最多同時執行4個進程。這是Pool有意設計的限制,並不是操作系統的限制。如果改成:
p = Pool(5)
就可以同時跑5個進程。
由於Pool的默認大小是CPU的核數,如果你不幸擁有8CPU,你要提交至少9個子進程才能看到上面的等待效果。
from multiprocessing import Pool
import os, time, random

def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Pool(4)
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()
    print('All subprocesses done.')

 

十 子進程

很多時候,子進程並不是自身,而是一個外部進程。我們創建了子進程後,還需要控制子進程的輸入和輸出。
subprocess模塊可以讓我們非常方便地啓動一個子進程,然後控制其輸入和輸出。
如果子進程還需要輸入,則可以通過communicate()方法輸入:
下面的例子演示瞭如何在Python代碼中運行命令nslookup www.python.org,這和命令行直接運行的效果是一樣的:

 

import subprocess

print('$ nslookup www.python.org')
r = subprocess.call(['nslookup', 'www.python.org'])
print('Exit code:', r)

print('$ nslookup')
p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = p.communicate(b'set q=mx\npython.org\nexit\n')
print(output.decode('utf-8'))
print('Exit code:', p.returncode)



發佈了317 篇原創文章 · 獲贊 115 · 訪問量 66萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章