当前位置:Gxlcms > Python > 举例详解Python中threading模块的几个常用方法

举例详解Python中threading模块的几个常用方法

时间:2021-07-01 10:21:17 帮助过:85人阅读

threading.Thread

Thread 是threading模块中最重要的类之一,可以使用它来创建线程。有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法;另一种是创建一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象作为参数传入。下面分别举例说明。先来看看通过继承threading.Thread类来创建线程的例子:

  1. #coding=gbk
  2. import threading, time, random
  3. count = 0
  4. class Counter(threading.Thread):
  5. def __init__(self, lock, threadName):
  6. '''@summary: 初始化对象。
  7. @param lock: 琐对象。
  8. @param threadName: 线程名称。
  9. '''
  10. super(Counter, self).__init__(name = threadName)
  11. #注意:一定要显式的调用父类的初始
  12. 化函数。
  13. self.lock = lock
  14. def run(self):
  15. '''@summary: 重写父类run方法,在线程启动后执行该方法内的代码。
  16. '''
  17. global count
  18. self.lock.acquire()
  19. for i in xrange(10000):
  20. count = count + 1
  21. self.lock.release()
  22. lock = threading.Lock()
  23. for i in range(5):
  24. Counter(lock, "thread-" + str(i)).start()
  25. time.sleep(2)
  26. #确保线程都执行完毕
  27. print count

在代码中,我们创建了一个Counter类,它继承了threading.Thread。初始化函数接收两个参数,一个是琐对象,另一个是线程的名称。在Counter中,重写了从父类继承的run方法,run方法将一个全局变量逐一的增加10000。在接下来的代码中,创建了五个Counter对象,分别调用其start方法。最后打印结果。这里要说明一下run方法 和start方法: 它们都是从Thread继承而来的,run()方法将在线程开启后执行,可以把相关的逻辑写到run方法中(通常把run方法称为活动[Activity]。);start()方法用于启动线程。

再看看另外一种创建线程的方法:

  1. import threading, time, random
  2. count = 0
  3. lock = threading.Lock()
  4. def doAdd():
  5. '''@summary: 将全局变量count 逐一的增加10000。
  6. '''
  7. global count, lock
  8. lock.acquire()
  9. for i in xrange(10000):
  10. count = count + 1
  11. lock.release()
  12. for i in range(5):
  13. threading.Thread(target = doAdd, args = (), name = 'thread-' + str(i)).start()
  14. time.sleep(2)
  15. #确保线程都执行完毕
  16. print count

在这段代码中,我们定义了方法doAdd,它将全局变量count 逐一的增加10000。然后创建了5个Thread对象,把函数对象doAdd 作为参数传给它的初始化函数,再调用Thread对象的start方法,线程启动后将执行doAdd函数。这里有必要介绍一下threading.Thread类的初始化函数原型:

  1. def __init__(self, group=None, target=None, name=None, args=(), kwargs={})

  •   参数group是预留的,用于将来扩展;
  •   参数target是一个可调用对象(也称为活动[activity]),在线程启动后执行;
  •   参数name是线程的名字。默认值为“Thread-N“,N是一个数字。
  •   参数args和kwargs分别表示调用target时的参数列表和关键字参数。

Thread类还定义了以下常用方法与属性:

  1. Thread.getName()
  2. Thread.setName()
  3. Thread.name

用于获取和设置线程的名称。

  1. Thread.ident

获取线程的标识符。线程标识符是一个非零整数,只有在调用了start()方法之后该属性才有效,否则它只返回None。

  1. Thread.is_alive()
  2. Thread.isAlive()

判断线程是否是激活的(alive)。从调用start()方法启动线程,到run()方法执行完毕或遇到未处理异常而中断 这段时间内,线程是激活的。

  1. Thread.join([timeout])

调用Thread.join将会使主调线程堵塞,直到被调用线程运行结束或超时。参数timeout是一个数值类型,表示超时时间,如果未提供该参数,那么主调线程将一直堵塞到被调线程结束。下面举个例子说明join()的使用:

  1. import threading, time
  2. def doWaiting():
  3. print 'start waiting:', time.strftime('%H:%M:%S')
  4. time.sleep(3)
  5. print 'stop waiting', time.strftime('%H:%M:%S')
  6. thread1 = threading.Thread(target = doWaiting)
  7. thread1.start()
  8. time.sleep(1)
  9. #确保线程thread1已经启动
  10. print 'start join'
  11. thread1.join()
  12. #将一直堵塞,直到thread1运行结束。
  13. print 'end join'

threading.RLock和threading.Lock

在threading模块中,定义两种类型的琐:threading.Lock和threading.RLock。它们之间有一点细微的区别,通过比较下面两段代码来说明:

  1. import threading
  2. lock = threading.Lock()
  3. #Lock对象
  4. lock.acquire()
  5. lock.acquire()
  6. #产生了死琐。
  7. lock.release()
  8. lock.release()
  9. import threading
  10. rLock = threading.RLock()
  11. #RLock对象
  12. rLock.acquire()
  13. rLock.acquire()
  14. #在同一线程内,程序不会堵塞。
  15. rLock.release()
  16. rLock.release()

这两种琐的主要区别是:RLock允许在同一线程中被多次acquire。而Lock却不允许这种情况。注意:如果使用RLock,那么acquire和release必须成对出现,即调用了n次acquire,必须调用n次的release才能真正释放所占用的琐。
threading.Condition

可以把Condiftion理解为一把高级的琐,它提供了比Lock, RLock更高级的功能,允许我们能够控制复杂的线程同步问题。threadiong.Condition在内部维护一个琐对象(默认是RLock),可以在创建Condigtion对象的时候把琐对象作为参数传入。Condition也提供了acquire, release方法,其含义与琐的acquire, release方法一致,其实它只是简单的调用内部琐对象的对应的方法而已。Condition还提供了如下方法(特别要注意:这些方法只有在占用琐(acquire)之后才能调用,否则将会报RuntimeError异常。):
Condition.wait([timeout]):

wait方法释放内部所占用的琐,同时线程被挂起,直至接收到通知被唤醒或超时(如果提供了timeout参数的话)。当线程被唤醒并重新占有琐的时候,程序才会继续执行下去。
Condition.notify():

唤醒一个挂起的线程(如果存在挂起的线程)。注意:notify()方法不会释放所占用的琐。

  1. Condition.notify_all()
  2. Condition.notifyAll()

唤醒所有挂起的线程(如果存在挂起的线程)。注意:这些方法不会释放所占用的琐。

现在写个捉迷藏的游戏来具体介绍threading.Condition的基本使用。假设这个游戏由两个人来玩,一个藏(Hider),一个找(Seeker)。游戏的规则如下:1. 游戏开始之后,Seeker先把自己眼睛蒙上,蒙上眼睛后,就通知Hider;2. Hider接收通知后开始找地方将自己藏起来,藏好之后,再通知Seeker可以找了; 3. Seeker接收到通知之后,就开始找Hider。Hider和Seeker都是独立的个体,在程序中用两个独立的线程来表示,在游戏过程中,两者之间的行为有一定的时序关系,我们通过Condition来控制这种时序关系。

  1. #---- Condition
  2. #---- 捉迷藏的游戏
  3. import threading, time
  4. class Hider(threading.Thread):
  5. def __init__(self, cond, name):
  6. super(Hider, self).__init__()
  7. self.cond = cond
  8. self.name = name
  9. def run(self):
  10. time.sleep(1)
  11. #确保先运行Seeker中的方法
  12. self.cond.acquire()
  13. #b
  14. print self.name + ': 我已经把眼睛蒙上了'
  15. self.cond.notify()
  16. self.cond.wait()
  17. #c
  18. #f
  19. print self.name + ': 我找到你了 ~_~'
  20. self.cond.notify()
  21. self.cond.release()
  22. #g
  23. print self.name + ': 我赢了'
  24. #h
  25. class Seeker(threading.Thread):
  26. def __init__(self, cond, name):
  27. super(Seeker, self).__init__()
  28. self.cond = cond
  29. self.name = name
  30. def run(self):
  31. self.cond.acquire()
  32. self.cond.wait()
  33. #a #释放对琐的占用,同时线程挂起在这里,直到被notify并重新占
  34. 有琐。
  35. #d
  36. print self.name + ': 我已经藏好了,你快来找我吧'
  37. self.cond.notify()
  38. self.cond.wait()
  39. #e
  40. #h
  41. self.cond.release()
  42. print self.name + ': 被你找到了,哎~~~'
  43. cond = threading.Condition()
  44. seeker = Seeker(cond, 'seeker')
  45. hider = Hider(cond, 'hider')
  46. seeker.start()
  47. hider.start()

threading.Event

Event实现与Condition类似的功能,不过比Condition简单一点。它通过维护内部的标识符来实现线程间的同步问题。(threading.Event和.NET中的System.Threading.ManualResetEvent类实现同样的功能。)
Event.wait([timeout])

堵塞线程,直到Event对象内部标识位被设为True或超时(如果提供了参数timeout)。
Event.set()

将标识位设为Ture
Event.clear()

将标识伴设为False。
Event.isSet()

判断标识位是否为Ture。

下面使用Event来实现捉迷藏的游戏(可能用Event来实现不是很形象)


  1. #---- Event
  2. #---- 捉迷藏的游戏
  3. import threading, time
  4. class Hider(threading.Thread):
  5. def __init__(self, cond, name):
  6. super(Hider, self).__init__()
  7. self.cond = cond
  8. self.name = name
  9. def run(self):
  10. time.sleep(1)
  11. #确保先运行Seeker中的方法
  12. print self.name + ': 我已经把眼睛蒙上了'
  13. self.cond.set()
  14. time.sleep(1)
  15. self.cond.wait()
  16. print self.name + ': 我找到你了 ~_~'
  17. self.cond.set()
  18. print self.name + ': 我赢了'
  19. class Seeker(threading.Thread):
  20. def __init__(self, cond, name):
  21. super(Seeker, self).__init__()
  22. self.cond = cond
  23. self.name = name
  24. def run(self):
  25. self.cond.wait()
  26. print self.name + ': 我已经藏好了,你快来找我吧'
  27. self.cond.set()
  28. time.sleep(1)
  29. self.cond.wait()
  30. print self.name + ': 被你找到了,哎~~~'
  31. cond = threading.Event()
  32. seeker = Seeker(cond, 'seeker')
  33. hider = Hider(cond, 'hider')
  34. seeker.start()
  35. hider.start()

threading.Timer

threading.Timer是threading.Thread的子类,可以在指定时间间隔后执行某个操作。下面是Python手册上提供的一个例子:

  1. def hello():
  2. print "hello, world"
  3. t = Timer(3, hello)
  4. t.start()
  5. # 3秒钟之后执行hello函数。

threading模块中还有一些常用的方法没有介绍:

  1. threading.active_count()
  2. threading.activeCount()

获取当前活动的(alive)线程的个数。

  1. threading.current_thread()
  2. threading.currentThread()

获取当前的线程对象(Thread object)。

  1. threading.enumerate()

获取当前所有活动线程的列表。
threading.settrace(func)

设置一个跟踪函数,用于在run()执行之前被调用。

  1. threading.setprofile(func)

设置一个跟踪函数,用于在run()执行完毕之后调用。

threading模块的内容很多,一篇文章很难写全,更多关于threading模块的信息,请查询Python手册 threading模块。

人气教程排行