Python3 多线程
发布日期:2021-05-14 05:44:50 浏览次数:15 分类:精选文章

本文共 3124 字,大约阅读时间需要 10 分钟。

Python3 多线程

多线程类似于同时执行多个不同程序,提供了显著的优势。首先,线程可以将占据长时间的任务放到后台处理,提升用户界面的响应速度。例如,用户点击按钮触发处理时,界面可以弹出进度条显示处理进度。其次,线程可以提高程序运行效率,特别是在涉及大量等待操作如文件读写和网络通信时,线程可以更好地释放资源如内存。最后,线程可以在执行过程中被抢占或暂停,这为程序设计提供了更高的灵活性。

需要注意的是,线程与进程有本质区别。每个线程都有自己的程序入口、执行顺序和程序出口,但线程无法独立运行,必须依赖应用程序提供执行控制。线程运行需要各自的上下文,包括CPU寄存器状态。在实际运行中,线程可以被抢占,即中断运行;也可以进入睡眠状态,等待其他线程或I/O操作完成。

线程模块

Python3 提供了两个主要线程模块:_thread和threading。其中thread模块已被废弃,threading模块提供了更高级别的功能,包括丰富的线程控制方法和线程同步机制。

使用threading模块创建线程

要使用threading模块创建线程,可以继承threading.Thread类并实现run方法。以下是一个示例:

from threading import Thread, enumerate
import time
class MyThread(Thread):
def __init__(self, name):
super().__init__(name)
self.count = 0
def run(self):
while self.count < 5:
time.sleep(1)
print(f"{self.name}: {time.strftime('%Y-%m-%d %H:%M:%S')}")
self.count += 1
thread1 = MyThread("Thread-1")
thread2 = MyThread("Thread-2")
thread1.start()
thread2.start()
for thread in enumerate():
if thread.isAlive():
print(f"当前活跃线程:{thread.name}")
else:
print(f"当前逗号线程:{thread.name}")
thread1.join()
thread2.join()
print("主线程退出")

线程同步

在多线程环境中共享数据时,为了确保数据一致性,必须使用同步机制。threading模块提供了ThreadLock和Rlock类,用于保护共享资源。以下是一个使用Rlock实现线程同步的示例:

from threading import Lock, enumerate
import time
class MyThread(Thread):
def __init__(self, name, lock):
super().__init__(name)
self.lock = lock
self.count = 0
def run(self):
while self.count < 5:
self.lock.acquire()
try:
self.count += 1
print(f"{self.name}: {self.count}")
finally:
self.lock.release()
time.sleep(1)
lock = Lock()
thread1 = MyThread("Thread-1", lock)
thread2 = MyThread("Thread-2", lock)
thread1.start()
thread2.start()
while True:
time.sleep(1)
break
thread1.join()
thread2.join()
print("主线程退出")

线程优先级队列(Queue)

当多个线程需要共享任务时,可以使用Queue模块来实现线程安全的数据传输。以下是一个使用队列实现任务分发的示例:

from queue import Queue
from threading import Thread
import time
class MyThread(Thread):
def __init__(self, name, queue):
super().__init__(name)
self.queue = queue
self.count = 0
def run(self):
while self.count < 5:
self.queue_lock.acquire()
try:
if not self.workQueue.empty():
data = self.workQueue.get()
print(f"{self.name}处理{data}")
self.count += 1
finally:
self.queue_lock.release()
time.sleep(1)
lock = Lock()
workQueue = Queue(maxsize=10)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
for tName in threadList:
thread = MyThread(tName, workQueue)
thread.start()
for word in ["One", "Two", "Three", "Four", "Five"]:
lock.acquire()
try:
workQueue.put(word)
finally:
lock.release()
while not workQueue.empty():
pass
exitFlag = 1
for thread in enumerate():
if not thread.is_alive():
continue
thread.join()
print("主线程退出")

上述代码演示了如何在多线程环境中使用threading模块实现线程创建、线程同步和队列通信。通过合理使用线程和同步机制,可以有效地管理多线程环境,避免数据竞争和不一致,提升程序的整体性能。

上一篇:ajax
下一篇:Python的线程join()方法

发表评论

最新留言

很好
[***.229.124.182]2025年04月15日 21时25分37秒