如何在Python中使用线程进行编程
线程有时被称为轻型进程,它们不需要太多的内存开销,比进程更便宜。线程有一个开始、一个执行序列和一个结束。
在Python3中,有两个支持使用线程的模块:
线程模块
Python 2.4中包含的新线程模块提供了比线程模块更强大、更高级的线程支持。
线程模块公开了线程模块的所有方法,并提供了一些额外的方法:
- threading.activeCount() - 返回当前活动的线程对象数。
-
threading.currentThread() - 返回调用线程控制的线程对象数。
-
threading.enumerate() - 返回当前活动的所有线程对象的列表。
线程模块有实现线程的Thread类。Thread类提供的方法如下:
- run() - run()方法是线程的入口点。
-
start() - start()方法通过调用run方法启动线程。
-
join([time]) - join()等待线程终止。
-
isAlive() - isAlive()方法检查线程是否仍在执行。
-
getName() - getName()方法返回线程的名称。
-
setName() - setName()方法设置线程的名称。
编写线程程序
与Python提供的线程配套的模块包括一种简单实现的锁定机制,该锁定机制允许您同步运行线程。通过调用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