当前位置:Gxlcms > Python > Python中多线程thread与threading的实现方法

Python中多线程thread与threading的实现方法

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

学过Python的人应该都知道,Python是支持多线程的,并且是native的线程。本文主要是通过thread和threading这两个模块来实现多线程的。

python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装的,可以更加方便的被使用。

这里需要提一下的是python对线程的支持还不够完善,不能利用多CPU,但是下个版本的python中已经考虑改进这点,让我们拭目以待吧。

threading模块里面主要是对一些线程的操作对象化了,创建了叫Thread的class。

一般来说,使用线程有两种模式,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里。

我们来看看这两种做法吧。

一、Python thread实现多线程

  1. #-*- encoding: gb2312 -*-
  2. import string, threading, time
  3. def thread_main(a):
  4. global count, mutex
  5. # 获得线程名
  6. threadname = threading.currentThread().getName()
  7. for x in xrange(0, int(a)):
  8. # 取得锁
  9. mutex.acquire()
  10. count = count + 1
  11. # 释放锁
  12. mutex.release()
  13. print threadname, x, count
  14. time.sleep(1)
  15. def main(num):
  16. global count, mutex
  17. threads = []
  18. count = 1
  19. # 创建一个锁
  20. mutex = threading.Lock()
  21. # 先创建线程对象
  22. for x in xrange(0, num):
  23. threads.append(threading.Thread(target=thread_main, args=(10,)))
  24. # 启动所有线程
  25. for t in threads:
  26. t.start()
  27. # 主线程中等待所有子线程退出
  28. for t in threads:
  29. t.join()
  30. if __name__ == '__main__':
  31. num = 4
  32. # 创建4个线程
  33. main(4)

二、Python threading实现多线程

  1. #-*- encoding: gb2312 -*-
  2. import threading
  3. import time
  4. class Test(threading.Thread):
  5. def __init__(self, num):
  6. threading.Thread.__init__(self)
  7. self._run_num = num
  8. def run(self):
  9. global count, mutex
  10. threadname = threading.currentThread().getName()
  11. for x in xrange(0, int(self._run_num)):
  12. mutex.acquire()
  13. count = count + 1
  14. mutex.release()
  15. print threadname, x, count
  16. time.sleep(1)
  17. if __name__ == '__main__':
  18. global count, mutex
  19. threads = []
  20. num = 4
  21. count = 1
  22. # 创建锁
  23. mutex = threading.Lock()
  24. # 创建线程对象
  25. for x in xrange(0, num):
  26. threads.append(Test(10))
  27. # 启动线程
  28. for t in threads:
  29. t.start()
  30. # 等待子线程结束
  31. for t in threads:
  32. t.join()

相信本文所述Python多线程实例对大家的Python程序设计能够起到一定的借鉴价值。

人气教程排行