多线程
多线程类似于同时执行多个不同程序,多线程运行有如下优点:
-
使用线程可以把占据长时间的程序中的任务放到后台去处理。
-
用户界面可以更加吸引人,比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度。
-
程序的运行速度可能加快。
-
在一些等待的任务实现上如用户输入、文件读写和网络收发数据等,线程就比较有用了。在这种情况下我们可以释放一些珍贵的资源如内存占用等等。
每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。但是线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制。
每个线程都有他自己的一组CPU寄存器,称为线程的上下文,该上下文反映了线程上次运行该线程的CPU寄存器的状态。
指令指针和堆栈指针寄存器是线程上下文中两个最重要的寄存器,线程总是在进程得到上下文中运行的,这些地址都用于标志拥有线程的进程地址空间中的内存。
-
线程可以被抢占(中断)。
-
在其他线程正在运行时,线程可以暂时搁置(也称为睡眠),这就是线程的退让。
线程可以分为:
-
内核线程:由操作系统内核创建和撤销。
-
用户线程:不需要内核支持而在用户程序中实现的线程。
Python中使用线程有两种方式:函数(方法)或者用类来包装线程对象。Python3通过两个标准库_thread
和线程模块threading
提供对线程的支持,其中 _thread
支持函数包装线程对象;threading
同时支持函数和类来包装线程对象。
_thread
_thread
提供了低级别的、原始的线程以及一个简单的锁,它相比于threading
模块的功能还是比较有限的。thread
模块已被废弃,在Python3中不能再使用thread
模块,可以使用threading
模块代替。为了兼容性,Python3将thread
重命名为_thread
。
调用_thread
模块中的start_new_thread()
函数来产生新线程。
语法:
_thread.start_new_thread(function, args[, kwargs])
import time
def print_time(thread_name, delay):
"""
定义一个线程函数
"""
count = 0
while count < 5:
time.sleep(delay)
print("%s: %s" % (thread_name, time.ctime(time.time())))
count += 1
import _thread
if __name__ == "__main__":
try:
_thread.start_new_thread(print_time, ("thread-1", 2))
_thread.start_new_thread(print_time, ("thread-2", 4))
# time.sleep(100) # 防止子线程还未结束,主进程就退出
except Exception as e:
print("Error: 无法启动线程,%s" % e)
thread-1: Tue May 12 09:58:18 2020
thread-2: Tue May 12 09:58:20 2020
thread-1: Tue May 12 09:58:20 2020
thread-1: Tue May 12 09:58:22 2020
thread-2: Tue May 12 09:58:24 2020
thread-1: Tue May 12 09:58:24 2020
thread-1: Tue May 12 09:58:26 2020
thread-2: Tue May 12 09:58:28 2020
thread-2: Tue May 12 09:58:32 2020
thread-2: Tue May 12 09:58:36 2020
threading
threading
模块(推荐)除了包含_thread
模块中的所有方法(在_thread
模块对应的方法名前加_
)外,还提供的其他方法:
-
threading.currentThread()
:返回当前的线程变量。 -
threading.enumerate()
:返回一个包含正在运行的线程的list
。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。 -
threading.activeCount()
:返回正在运行的线程数量,与len(threading.enumerate())
结果相同。
import time
def print_time(thread_name, delay):
"""
定义一个线程函数
"""
count = 0
while count < 5:
time.sleep(delay)
print("%s: %s" % (thread_name, time.ctime(time.time())))
count += 1
import threading
if __name__ == "__main__":
try:
threading._start_new_thread(print_time, ("thread-1", 2))
threading._start_new_thread(print_time, ("thread-2", 4))
print("{}个线程正在运行:{}".format(threading.activeCount(), threading.enumerate()))
# time.sleep(100) # 防止子线程还未结束,主进程就退出
except Exception as e:
print("Error: 无法启动线程,%s" % e)
5个线程正在运行:[<_MainThread(MainThread, started 26812)>, <Thread(Thread-4, started daemon 6040)>, <Heartbeat(Thread-5, started daemon 39492)>, <HistorySavingThread(IPythonHistorySavingThread, started 31216)>, <ParentPollerWindows(Thread-3, started daemon 33516)>]
thread-1: Tue May 12 09:59:05 2020
thread-2: Tue May 12 09:59:07 2020
thread-1: Tue May 12 09:59:07 2020
thread-1: Tue May 12 09:59:09 2020
thread-2: Tue May 12 09:59:11 2020
thread-1: Tue May 12 09:59:11 2020
thread-1: Tue May 12 09:59:13 2020
thread-2: Tue May 12 09:59:15 2020
thread-2: Tue May 12 09:59:19 2020
thread-2: Tue May 12 09:59:23 2020
线程模块threading
同时提供了Thread
类处理线程,Thread
类的方法:
-
run()
:用以表示线程活动的方法。 -
start()
:启动线程活动。 -
join([time])
:等待至线程中止。这阻塞调用线程直至线程的join()
方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。 -
isAlive()
:返回线程是否活动的。 -
getName()
:返回线程名。 -
setName()
:设置线程名。
直接从threading.Thread
继承创建一个新的子类并实例化,然后调用start()
方法启动新线程,即它调用了线程的run()
方法:
from typing import Text
from threading import Thread
import time
def print_time(thread_name, delay, counter):
"""
定义一个线程函数
"""
while counter:
time.sleep(delay)
print("%s: %s" % (thread_name, time.ctime(time.time())))
counter -= 1
class ConcreteThread(Thread):
def __init__(self, thread_id: int, name: Text, delay: int) -> None:
super(ConcreteThread, self).__init__()
self.thread_id = thread_id
self.name = name
self.delay = delay
def run(self):
print("开始线程:" + self.name)
print_time(self.name, self.delay, 5)
print("退出线程:" + self.name)
if __name__ == "__main__":
# 创建新线程
thread1 = ConcreteThread(1, "Thread-1", 1)
thread2 = ConcreteThread(2, "Thread-2", 2)
# 开启新线程
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("退出主线程")
开始线程:Thread-1
开始线程:Thread-2
Thread-1: Tue May 12 10:02:35 2020
Thread-1: Tue May 12 10:02:36 2020
Thread-2: Tue May 12 10:02:36 2020
Thread-1: Tue May 12 10:02:37 2020
Thread-1: Tue May 12 10:02:38 2020
Thread-2: Tue May 12 10:02:38 2020
Thread-1: Tue May 12 10:02:39 2020
退出线程:Thread-1
Thread-2: Tue May 12 10:02:40 2020
Thread-2: Tue May 12 10:02:42 2020
Thread-2: Tue May 12 10:02:44 2020
退出线程:Thread-2
退出主线程
线程同步
多线程的优势在于可以同时运行多个任务(至少感觉起来是这样)。但是当线程需要共享数据时,可能存在数据不同步的问题(例:多个线程共同对某个数据修改)。为了保证数据的正确性,需要对多个线程进行同步,从而引入锁的概念。锁有两种状态:锁定
(同步阻塞)和未锁定
。使用threading
模块的Lock
类和Rlock
类可以实现简单的线程同步,这两个类都有acquire
方法和release
方法,对于每次只允许一个线程操作的数据,可以将其操作放到acquire
和release
方法之间。
from typing import Text
from threading import Lock, Thread
import time
def print_time(thread_name, delay, counter):
"""
定义一个线程函数
"""
while counter:
time.sleep(delay)
print("%s: %s" % (thread_name, time.ctime(time.time())))
counter -= 1
class ConcreteThread(Thread):
def __init__(self, thread_id: int, name: Text, delay: int, thread_lock: Lock) -> None:
super(ConcreteThread, self).__init__()
self.thread_id = thread_id
self.name = name
self.delay = delay
self.thread_lock = thread_lock
def run(self):
print("开始线程:" + self.name)
# 获取锁,用于线程同步
self.thread_lock.acquire()
print_time(self.name, self.delay, 5)
# 释放锁,开启下一个线程
self.thread_lock.release()
print("退出线程:" + self.name)
if __name__ == "__main__":
thread_lock = Lock()
threads = []
# 创建新线程
thread1 = ConcreteThread(1, "Thread-1", 1, thread_lock)
threads.append(thread1)
thread2 = ConcreteThread(2, "Thread-2", 2, thread_lock)
threads.append(thread2)
# 开启新线程
for t in threads:
t.start()
# 等待所有线程完成
for t in threads:
t.join()
print ("退出主线程")
开始线程:Thread-1
开始线程:Thread-2
Thread-1: Tue May 12 10:03:37 2020
Thread-1: Tue May 12 10:03:38 2020
Thread-1: Tue May 12 10:03:39 2020
Thread-1: Tue May 12 10:03:40 2020
Thread-1: Tue May 12 10:03:41 2020
退出线程:Thread-1
Thread-2: Tue May 12 10:03:43 2020
Thread-2: Tue May 12 10:03:45 2020
Thread-2: Tue May 12 10:03:47 2020
Thread-2: Tue May 12 10:03:49 2020
Thread-2: Tue May 12 10:03:51 2020
退出线程:Thread-2
退出主线程
线程优先级队列
queue
模块中提供了同步的、线程安全的队列类,包括FIFO
(先入先出)队列类Queue
,LIFO
(后入先出)队列类LifoQueue
,和优先级队列类PriorityQueue
。
这些队列都实现了锁原语,能够在多线程中直接使用,可以使用队列来实现线程间的同步。
Queue
类中的常用方法:
-
Queue(maxsize)
实例化对象 -
Queue.qsize()
返回队列的大小 -
Queue.empty()
如果队列为空,返回True,反之False -
Queue.full()
如果队列满了,返回True,反之False。Queue.full()
与maxsize
大小对应 -
Queue.get([block[, timeout]])
获取队列,timeout
为等待时间 -
Queue.get_nowait()
相当Queue.get(False)
-
Queue.put(item[, timeout]])
写入队列,timeout
为等待时间 -
Queue.put_nowait(item)
相当Queue.put(item, False)
-
Queue.task_done()
在完成一项工作之后,Queue.task_done()
函数向任务已经完成的队列发送一个信号 -
Queue.join()
实际上意味着等到队列为空,再执行别的操作
from queue import Queue
from threading import Lock, Thread
from typing import Text
import time
class ConcreteThread(Thread):
def __init__(self, thread_id: int, name: Text, thread_lock: Lock, q: Queue) -> None:
super(ConcreteThread, self).__init__()
self.thread_id = thread_id
self.name = name
self.thread_lock = thread_lock
self.q = q
def run(self):
print("开始线程:" + self.name)
process_data(self.name, self.thread_lock, self.q)
print("退出线程:" + self.name)
def process_data(thread_name: Text, thread_lock: Lock, q: Queue):
while not EXIT_FLAG:
thread_lock.acquire()
if not q.empty():
data = q.get()
print("{} processing {}".format(thread_name, data))
thread_lock.release()
time.sleep(1)
if __name__ == "__main__":
EXIT_FLAG = 0
thread_names = ["Thread-1", "Thread-2", "Thread-3"]
threads = []
data = ["One", "Two", "Three", "Four", "Five"]
thread_lock = Lock()
work_queue = Queue(maxsize=10)
# 创建新线程
for thread_id, thread_name in enumerate(thread_names):
thread = ConcreteThread(thread_id, thread_name, thread_lock, work_queue)
thread.start()
threads.append(thread)
# 填充队列
thread_lock.acquire()
for term in data:
work_queue.put(term)
thread_lock.release()
# 等待队列清空
while not work_queue.empty():
pass
print("第一次队列清空")
# 再次填充队列
thread_lock.acquire()
for term in data:
work_queue.put(term)
thread_lock.release()
# 等待队列清空
while not work_queue.empty():
pass
print("第二次队列清空")
# 通知线程是时候退出了
EXIT_FLAG = 1
# 等待所有线程完成
for t in threads:
t.join()
print ("退出主线程")
开始线程:Thread-1
开始线程:Thread-2
开始线程:Thread-3
Thread-3 processing One
Thread-1 processing Two
Thread-2 processing Three
Thread-3 processing Four
Thread-1 processing Five第一次队列清空
Thread-2 processing One
Thread-3 processing Two
Thread-1 processing Three
Thread-2 processing Four
Thread-3 processing Five第二次队列清空
退出线程:Thread-1退出线程:Thread-2
退出线程:Thread-3
退出主线程