使用 threading 模块创建线程
可以通过从 threading.Thread 继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即它调用了线程的 run() 方法。
实战(Python3环境)
import threading
import time
class MyThread(threading.Thread):
def __init__(self, threadID, name, delay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.delay = delay
def run(self):
print("开始线程:" + self.name)
print_time(self.name, self.delay, 5)
print("退出线程:" + self.name)
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print("%s: %s" %(threadName, time.ctime(time.time())))
counter -= 1
t1 = MyThread(1, "t1", 1)
t2 = MyThread(2, "t2", 2)
t1.start()
t2.start()
t1.join()
t2.join()
print ("退出主线程")
运行结果:
开始线程:t1
开始线程:t2
t1: Sat Jul 6 15:44:58 2019
t2: Sat Jul 6 15:44:59 2019
t1: Sat Jul 6 15:44:59 2019
t1: Sat Jul 6 15:45:00 2019
t2: Sat Jul 6 15:45:01 2019
t1: Sat Jul 6 15:45:01 2019
t1: Sat Jul 6 15:45:02 2019
退出线程:t1
t2: Sat Jul 6 15:45:03 2019
t2: Sat Jul 6 15:45:05 2019
t2: Sat Jul 6 15:45:07 2019
退出线程:t2
退出主线程
线程同步
如果多个线程共同对某个数据进行修改,则可能出现不可预料的结果,为了保证数据的正确性,需要对多个线程进行同步。 使用 Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到 acquire 和 release 方法之间。
实战(Python3环境)
from threading import Lock, Thread
lock = Lock()
g = 0
# global 加1
def add_one():
global g
lock.acquire()
g += 1
lock.release()
# global 加2
def add_two():
global g
lock.acquire()
g += 2
lock.release()
threads = []
for func in [add_one, add_two]:
threads.append(Thread(target = func))
threads.append(Thread(target = func))
for t in threads:
t.start()
t.join()
print(g)
运行结果
6
- Python 多线程编程,容易发生数据读写冲突,必须用锁加以隔离,又要小心死锁的发生。
多核 CPU
在 Windows 的 Task Manager 中可以监控某个进程的 CPU 使用率。一般每一个死循环线程会 100% 占用一个 CPU。如果有两个死循环线程,在多核 CPU 中,可以监控到会占用 200% 的 CPU,也就是占用两个 CPU 核心。要想把 N 核 CPU 的核心全部跑满,就必须启动 N 个死循环线程。但是 Python 却不是这样的。
实战(Python3环境)
import threading, multiprocessing
def loop():
x = 0
while True:
x = x + 1
print(x)
for i in range(multiprocessing.cpu_count()):
t = threading.Thread(target=loop)
t.start()
运行结果:
0
1
20
1
2
3
...
-
multiprocessing.cpu_count() 可以获得 CPU 的核数,我的计算机核数是 4,理论上应该占用了 400%,但是实际上通过 活动监视器可以发现是只有 100.6%,仅用了一核的样子。
-
因为 Python 的线程虽然是真正的线程,但解释器执行代码时,有一个 GIL 锁:Global Interpreter Lock,任何 Python 线程执行前,必须先获得 GIL 锁,然后,每执行 100 条字节码,解释器就自动释放 GIL 锁,让别的线程有机会执行。
-
这个 GIL 全局锁实际上把所有线程的执行代码都给上了锁,所以多线程在 Python 中只能交替执行,即使 100 个线程跑在 100 核 CPU 上,也只能用到 1 个核。Python 解释器由于设计时有 GIL 全局锁,导致了多线程无法利用多核。多线程的并发 Python 中就是一个美丽的梦。
-
GIL 是 Python 解释器设计的历史遗留问题,通常我们用的解释器是官方实现的 CPython ,要真正利用多核,除非重写一个不带 GIL 的解释器。
-
所以在 Python 中,可以使用多线程,但不要指望能有效利用多核。如果一定要通过多线程利用多核,那只能通过 C 扩展来实现,不过这样就失去了 Python 简单易用的特点。
-
不过也不用过于担心,Python 虽然不能利用多线程实现多核任务,但可以通过多进程实现多核任务。多个 Python 进程有各自独立的 GIL 锁,互不影响。
线程优先级队列(Queue)
-
Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列 Queue,LIFO(后入先出)队列 LifoQueue,和优先级队列 PriorityQueue。
-
这些队列都实现了锁原语,能够在多线程中直接使用,可以使用队列来实现线程间的同步。
实战(Python3环境)
import queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print ("开启线程:" + self.name)
process_data(self.name, self.q)
print ("退出线程:" + self.name)
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print ("%s processing %s" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
# 创建新线程
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# 填充队列
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# 等待队列清空
while not workQueue.empty():
pass
# 通知线程是时候退出
exitFlag = 1
# 等待所有线程完成
for t in threads:
t.join()
print ("退出主线程")
运行结果:
开启线程:Thread-1
开启线程:Thread-2
开启线程:Thread-3
Thread-3 processing One
Thread-2 processing Two
Thread-1 processing Three
Thread-3 processing Four
Thread-2 processing Five
退出线程:Thread-3
退出线程:Thread-1
退出线程:Thread-2
退出主线程
本文参考:
菜鸟:www.runoob.com/python3/pyt… 廖雪峰:www.liaoxuefeng.com/wiki/101695…
希望看客老爷打赏些喝茶钱
支付宝