方法一:threading.Thread

1.1 原理

Python多线程编程(一):threading 模块 Thread 类的用法详解
https://blog.csdn.net/briblue/article/details/85101144

1.2 代码

  1. import threading
  2. import time
  3. exitFlag = 0
  4. class myThread(threading.Thread):
  5. def __init__(self, threadID, name, delay):
  6. threading.Thread.__init__(self)
  7. self.threadID = threadID
  8. self.name = name
  9. self.delay = delay
  10. def run(self):
  11. print("开始线程:" + self.name)
  12. print_time(self.name, self.delay, 5)
  13. print("退出线程:" + self.name)
  14. def print_time(threadName, delay, counter):
  15. while counter:
  16. if exitFlag:
  17. threadName.exit()
  18. time.sleep(delay)
  19. print("%s: %s" % (threadName, time.ctime(time.time())))
  20. counter -= 1
  21. # 创建新线程
  22. thread1 = myThread(1, "Thread-1", 1)
  23. thread2 = myThread(2, "Thread-2", 2)
  24. # 开启新线程
  25. thread1.start()
  26. thread2.start()
  27. thread1.join()
  28. thread2.join()
  29. print("退出主线程")

1.3 输出:

  1. 开始线程:Thread-1
  2. 开始线程:Thread-2
  3. Thread-1: Tue Feb 8 21:22:51 2022
  4. Thread-2: Tue Feb 8 21:22:52 2022
  5. Thread-1: Tue Feb 8 21:22:52 2022
  6. Thread-1: Tue Feb 8 21:22:53 2022
  7. Thread-2: Tue Feb 8 21:22:54 2022
  8. Thread-1: Tue Feb 8 21:22:54 2022
  9. Thread-1: Tue Feb 8 21:22:55 2022

方法二:multiprocessing.dummy

2.1 参考资料

一行 Python 代码实现并行
https://mp.weixin.qq.com/s/akNhoFW4rF3g1OecGprGjQ

2.2 代码

  1. import urllib.request
  2. from multiprocessing.dummy import Pool as ThreadPool
  3. from functools import wraps
  4. import time
  5. def func_timer(function):
  6. '''
  7. 用装饰器实现函数计时
  8. :param function: 需要计时的函数
  9. :return: None
  10. '''
  11. @wraps(function)
  12. def function_timer(*args, **kwargs):
  13. t0 = time.time()
  14. result = function(*args, **kwargs)
  15. t1 = time.time()
  16. print('[Function: {name} finished, spent time: {time:.2f}s]'.format(name=function.__name__, time=t1 - t0))
  17. return result
  18. return function_timer
  19. urls = [
  20. 'https://www.baidu.com',
  21. 'https://www.baidu.com',
  22. 'https://www.baidu.com',
  23. 'https://www.baidu.com',
  24. 'https://www.baidu.com',
  25. 'https://www.baidu.com',
  26. 'https://www.baidu.com',
  27. 'https://www.baidu.com',
  28. 'https://www.baidu.com',
  29. 'https://www.baidu.com',
  30. 'https://www.baidu.com',
  31. 'https://www.baidu.com',
  32. 'https://www.baidu.com',
  33. 'https://www.baidu.com',
  34. 'https://www.baidu.com',
  35. # etc..
  36. ]
  37. @func_timer
  38. def singleThread():
  39. results = []
  40. for url in urls:
  41. result = urllib.request.urlopen(url)
  42. results.append(result)
  43. print('Thread-single')
  44. @func_timer
  45. def pool(n):
  46. pool = ThreadPool(n)
  47. # Open the urls in their own threads
  48. # and return the results
  49. results = pool.map(urllib.request.urlopen, urls)
  50. print('Thread-%s' % str(n))
  51. if __name__ == '__main__':
  52. singleThread()
  53. pool(4)
  54. pool(8)
  55. pool(12)

2.3 输出

  1. Thread-single
  2. [Function: singleThread finished, spent time: 1.80s]
  3. Thread-4
  4. [Function: pool finished, spent time: 0.57s]
  5. Thread-8
  6. [Function: pool finished, spent time: 0.27s]
  7. Thread-12
  8. [Function: pool finished, spent time: 0.24s]