Python 中的 Threading 模块

pythonserver side programmingprogramming更新于 2025/5/7 7:08:17

Python 2.4 中包含的较新的 threading 模块比上一节讨论的 thread 模块提供了更强大、更高级的线程支持。

threading 模块公开了 thread 模块的所有方法,并提供了一些附加方法 −

  • threading.activeCount() − 返回处于活动状态的线程对象的数量。
  • threading.currentThread() − 返回调用方线程控制中的线程对象的数量。
  • threading.enumerate() −返回当前处于活动状态的所有线程对象的列表。

除了方法之外,threading 模块还具有实现线程的 Thread 类。Thread 类提供的方法如下 −

  • run()  − run() 方法是线程的入口点。
  • start()  − start() 方法通过调用 run 方法来启动线程。
  • join([time])  − join() 等待线程终止。
  • isAlive()  − isAlive() 方法检查线程是否仍在执行。
  • getName()  − getName() 方法返回线程的名称。
  • setName()  − setName() 方法设置线程的名称。

使用 Threading 模块创建线程

要使用 threading 模块实现新线程,您必须执行以下操作 −

  • 定义 Thread 类的新子类。
  • 重写 __init__(self [,args]) 方法以添加其他参数。
  • 然后,重写 run(self [,args]) 方法以实现线程启动时应执行的操作。

创建新的 Thread 子类后,您可以创建它的一个实例,然后通过调用 start() 来启动新线程,这反过来调用 run() 方法。

示例

#!/usr/bin/python
import threading
import time
exitFlag = 0
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
      print_time(self.name, 5, self.counter)
      print "Exiting " + self.name
def print_time(threadName, counter, delay):
   while counter:
      if exitFlag:
         threadName.exit()
      time.sleep(delay)
      print "%s: %s" % (threadName, time.ctime(time.time()))
      counter -= 1
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 启动新线程
thread1.start()
thread2.start()
print "Exiting Main Thread"

执行上述代码时,会产生以下结果 −

Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2

相关文章


有用资源