1. Python多線程介紹
Python提供了兩個(gè)有關(guān)多線程的標(biāo)準(zhǔn)庫,thread
和threading
。thread
提供了低級別的,原始的線程和一個(gè)鎖。threading
則是一個(gè)高級模塊,提供了對thread
的封裝。一般情況下,使用threading
是比較好的做法。
使用threading
實(shí)現(xiàn)線程,只需要從threading.Thread
類繼承,并重寫其中的__init__()
方法和run()
方法。
from threading import Thread
class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
print(self.thread_id, "start")
threading
提供了一個(gè)鎖:lock = threading.Lock()
,調(diào)用鎖的acquire()
和release()
方法可以使線程獲得和釋放鎖。
需要注意的是,Python有一個(gè)GIL(Global Interpreter Lock)機(jī)制,任何線程在運(yùn)行之前必須獲取這個(gè)全局鎖才能執(zhí)行,每當(dāng)執(zhí)行完100條字節(jié)碼,全局鎖才會釋放,切換到其他線程執(zhí)行。
所以Python中的多線程不能利用多核計(jì)算機(jī)的優(yōu)勢,無論有多少個(gè)核,同一時(shí)間只有一個(gè)線程能得到全局鎖,只有一個(gè)線程能夠運(yùn)行。
那么Python中的多線程有什么作用呢?為什么不直接使用Python中的多進(jìn)程標(biāo)準(zhǔn)庫?這里要根據(jù)程序執(zhí)行的是IO密集型任務(wù)和計(jì)算密集型任務(wù)來選擇。
當(dāng)執(zhí)行IO密集型任務(wù)時(shí),比如Python爬蟲,大部分時(shí)間都用在了等待返回的socket數(shù)據(jù)上,CPU此時(shí)是完全閑置的,這種情況下采用多線程較好。
當(dāng)執(zhí)行計(jì)算密集型任務(wù)時(shí),比如圖像處理,大部分時(shí)間CPU都在計(jì)算,這種情況下使用多進(jìn)程才能真正的加速,使用多線程不僅得不到并行加速的效果,反而因?yàn)轭l繁切換上下文拖慢了速度。
2. threading實(shí)現(xiàn)生產(chǎn)者消費(fèi)者
# -*- coding: utf-8 -*-
from threading import Thread
import time
queue = []
class Producer(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
while 1:
queue.append(1)
print("Producer: %s create a product" % self.name)
print("Producer: %s put a product into queue" % self.name)
time.sleep(0)
if len(queue) > 20:
print("queue is full!")
time.sleep(1)
class Consumer(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
while 1:
try:
queue.pop()
print("Consumer: %s get a product" % self.name)
time.sleep(2)
except:
print("Queue is empty!")
time.sleep(2)
print("Consumer: %s sleep 2 seconds" % self.name)
def test():
p1 = Producer("Producer-1")
c1 = Consumer("Consumer-1")
c2 = Consumer("consumer-2")
p1.start()
c1.start()
c2.start()
if __name__ == "__main__":
test()
輸出如下:
Producer: Producer-1 create a product
Producer: Producer-1 put a product into queue
queue is full!
Producer: Producer-1 create a product
Producer: Producer-1 put a product into queue
queue is full!
輸出顯示滿了之后仍然顯示了生產(chǎn)者在創(chuàng)建產(chǎn)品,表明線程run()方法中的運(yùn)行次序被打亂了。這是因?yàn)闆]有加鎖,導(dǎo)致消費(fèi)者線程運(yùn)行到一半的時(shí)候,生產(chǎn)者線程獲得了CPU。
Python提供了queue
這一線程安全的容器,可以方便的和多線程結(jié)合起來。 queue
包括FIFO先入先出隊(duì)列Queue,LIFO后入先出隊(duì)列LifoQueue,和優(yōu)先級隊(duì)列PriorityQueue。這些隊(duì)列都實(shí)現(xiàn)了鎖原語,能夠在多線程中直接使用。可以使用隊(duì)列來實(shí)現(xiàn)線程間的同步。
queue_tmp = queue.Queue(10)
class Producer(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
while 1:
queue_tmp.put(0)
print("Producer: %s create a product" % self.name)
print("Producer: %s put a product into queue" % self.name)
class Consumer(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
while 1:
queue_tmp.get()
print("Consumer: %s get a product" % self.name)
3. join()函數(shù)用法測試
join()
函數(shù)的原型是join(timeout=None)
,它的作用是阻塞進(jìn)程一直到線程退出或者到timeout的時(shí)間結(jié)束。
這樣一說是比較抽象的,下面用例子說明。
# -*- coding: utf-8 -*-
import threading
from threading import Thread
import time
lock = threading.Lock()
class MyThread(Thread):
def __init__(self, thread_id, thread_name, thread_counter):
Thread.__init__(self)
self.thread_id = thread_id
self.thread_name = thread_name
self.thread_counter = thread_counter
def run(self):
print(self.thread_id, "start")
self.print_time(self.thread_name, self.thread_counter, 2)
print(self.thread_id, "end")
@staticmethod
def print_time(thread_name, thread_counter, delay):
for i in range(thread_counter):
time.sleep(delay)
print("%s: %s" % (thread_name, time.ctime(time.time())))
def test():
t1 = MyThread(1, "Thread1", 5)
t2 = MyThread(2, "Thread2", 5)
t3 = MyThread(3, "Thread3", 5)
t1.start()
t2.start()
t3.start()
if __name__ == "__main__":
test()
程序中的三個(gè)線程均未調(diào)用join()方法,輸出如下:
1 start
2 start
3 start
Thread2: Thu Sep 8 20:53:06 2016
Thread1: Thu Sep 8 20:53:06 2016
Thread3: Thu Sep 8 20:53:06 2016
Thread1: Thu Sep 8 20:53:08 2016
Thread2: Thu Sep 8 20:53:08 2016
Thread3: Thu Sep 8 20:53:08 2016
...
可以看到,三個(gè)線程開始后交替執(zhí)行,下面給t2線程加入join()方法:
def test():
t1 = MyThread(1, "Thread1", 5)
t2 = MyThread(2, "Thread2", 5)
t3 = MyThread(3, "Thread3", 5)
t1.start()
t2.start()
t2.join()
t3.start()
輸出變成了下面這樣:
1 start
2 start
Thread1: Thu Sep 8 20:54:58 2016
Thread2: Thu Sep 8 20:54:58 2016
Thread1: Thu Sep 8 20:55:00 2016
...
2 end
Thread1: Thu Sep 8 20:55:39 2016
1 end
3 start
t1和t2交替執(zhí)行,直到t2結(jié)束之后,才會不再阻塞進(jìn)程,繼續(xù)執(zhí)行t3.start()。
所以,join()函數(shù)是可以執(zhí)行線程之間同步的。不過它最常用的是在啟動(dòng)了一批線程之后,逐個(gè)調(diào)用每個(gè)線程的join()方法,阻塞當(dāng)前進(jìn)程,直到每個(gè)線程都退出。