如何在Python中使用线程编程
线程有时被称为轻量级进程,它们不需要大量的内存开销;它们比进程更便宜。线程有一个开始,一个执行序列和一个结束。
Python 3中有两个模块支持线程的使用:
_thread − Python 3中已弃用
threading − 在Python 2.4中引入
threading模块
Python 2.4中包含的较新的threading模块比thread模块提供了更强大、更高级别的线程支持。
threading模块公开了thread模块的所有方法,并提供了一些附加方法:
threading.activeCount() − 返回正在活动的线程对象数量。
threading.currentThread() − 返回调用方线程控制中的线程对象数量。
threading.enumerate() − 返回当前正在活动的所有线程对象的列表。
threading模块包含实现threading的Thread类。Thread类提供的方法如下:
run() − run()方法是线程的入口点。
start() − start()方法通过调用run方法来启动线程。
join([time]) − join()等待线程终止。
isAlive() − isAlive()方法检查线程是否仍在执行。
getName() − getName()方法返回线程的名称。
setName() − setName()方法设置线程的名称。
编写线程程序
Python提供的threading模块包含一个易于实现的锁机制,允许您同步线程。通过调用Lock()方法创建一个新的锁,该方法返回新的锁。
新锁对象的acquire(blocking)方法用于强制线程同步运行。可选的blocking参数允许您控制线程是否等待获取锁。如果blocking设置为0,则如果无法获取锁,线程立即返回0值;如果获取了锁,则返回1。如果blocking设置为1,则线程阻塞并等待锁被释放。
示例
新锁对象的release()方法用于在不再需要锁时释放锁。
import threading import time class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print ("Starting " + self.name) # Get lock to synchronize threads threadLock.acquire() print_time(self.name, self.counter, 3) # Free lock to release next thread threadLock.release() def print_time(threadName, delay, counter): while counter: time.sleep(delay) print ("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 threadLock = threading.Lock() threads = [] # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() # Add threads to thread list threads.append(thread1) threads.append(thread2) # Wait for all threads to complete for t in threads: t.join() print ("Exiting Main Thread")
输出
Starting Thread-1 Starting Thread-2 Thread-1: Mon Sep 19 08:57:59 2022 Thread-1: Mon Sep 19 08:58:00 2022 Thread-1: Mon Sep 19 08:58:01 2022 Thread-2: Mon Sep 19 08:58:03 2022 Thread-2: Mon Sep 19 08:58:05 2022 Thread-2: Mon Sep 19 08:58:07 2022 Exiting Main Thread
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP