前言

本文将介绍python中的多线程使用方法,信号量,线程间通讯,注意事项及实例。

多线程

由于全局锁的限制,python的多线程无法充分利用多核CPU,但是对于IO密集型的任务,例如读写文件,爬虫中的页面请求,我们仍然可以使用多线程来提高程序运行的效率。

python中的多线程我们一般可以通过内建模块threading来实现,而线程中常常涉及到以下几个问题:

  1. 一个是信号量的问题,也就是限制同时存在的线程数,这个可以通过threading 模块中的semphore函数来实现;
  2. 第二个问题是线程间的资源共享问题,多个线程同时操作一个文件会有安全问题,这个问题可以通过锁来解决,threading模块中的Lock和重用锁RLock可以用来实现锁的功能,二者的主要区别是后者可以被同一个线程多次获取,而前者仅能被获取一次,只有在释放过后才可以再被其他线程获取;
  3. 第三个问题是线程间的通讯问题,该问题可以使用模块queue中的Queue队列来实现,该函数提供了put和get方法来放置和获取元素
  4. 线程异常的问题,一个线程如果报错,正常不会影响到其他线程和主线程,为了从主线程获取子线程的报错,我们这里需要一些小技巧来实现,例如我们可以编写一个装饰器函数来给线程对象添加该线程中执行的函数的状态码和报错信息。

    异常处理及信号量解决方案

其中第一个和第四个问题可以通过如下构建的一个装饰器来实现:

  1. def thread_enhance(thread=None):
  2. """
  3. A decorator to provide semaphore and exception handle function
  4. for mutiple threading
  5. ------------------------
  6. thread: number of thread [integer]
  7. """
  8. sema = Semaphore(thread) if thread else None
  9. def decorator(func):
  10. def wrapper(*args,**kwargs):
  11. class TH(Thread):
  12. def __init__(self):
  13. super().__init__()
  14. self.error = 0
  15. self.msg = "ok"
  16. def run(self):
  17. if sema:
  18. sema.acquire()
  19. try:
  20. func(*args,**kwargs)
  21. except Exception as e:
  22. pass
  23. print("exception happened!")
  24. self.error = 1
  25. self.msg = e
  26. if sema:
  27. sema.release()
  28. return TH()
  29. return wrapper
  30. return decorator

上述的装饰器的核心思想是继承Thread类并重写run方法。该装饰器除了可以提供线程的异常处理以外,还可以提供信号量的功能,只需要给thread添加一个参数即可限制同时开启的线程数量。
使用该装饰器,我们就可以在主线程获取线程的报错并进行处理,如下例子:

  1. @thread_enhance()
  2. def func():
  3. print(f"Current threading:{current_thread().name}")
  4. print("start run ...")
  5. print(1/0)
  6. def func_test():
  7. th = func()
  8. th.start()
  9. th.join()
  10. if th.error != 0:
  11. print(th.msg)
  12. else:
  13. print("No error in thread")
  14. print("main thread end.")

运行上述的func_test函数将得到以下输出:

  1. $python threading_example.py
  2. Current threading:Thread-1
  3. start run ...
  4. exception happened!
  5. division by zero
  6. main thread end

信号量的使用示例如下:
首先构建一个测试函数,我们中间随机睡眠1到3秒

  1. @thread_enhance(3)
  2. def run():
  3. print(f"Current threading:{current_thread().name}")
  4. print("start run ...")
  5. time.sleep(random.randint(1,3))
  6. print("end run...")

然后我们循环使用该测试函数来开启线程,但是同时我们将只能允许开启三个线程

  1. def muti_thread_run():
  2. ths = []
  3. for _ in range(10):
  4. th = run()
  5. th.start()
  6. ths.append(th)
  7. for th in ths:
  8. th.join()

这里特别需要注意的是ths这个列表,该列表用于存放开启的多个线程,并阻塞它们,让主进程在等待子线程完成后再运行。

运行上述函数将得到如下的输出结果:

  1. $ python threading_example.py
  2. Current threading:Thread-1
  3. Current threading:Thread-2
  4. start run ...
  5. Current threading:Thread-3
  6. start run ...
  7. start run ...
  8. end run...
  9. Current threading:Thread-4
  10. start run ...
  11. end run...
  12. Current threading:Thread-5
  13. start run ...
  14. end run...
  15. Current threading:Thread-6
  16. start run ...
  17. end run...
  18. Current threading:Thread-7
  19. start run ...
  20. end run...
  21. Current threading:Thread-8
  22. start run ...
  23. end run...
  24. Current threading:Thread-9
  25. start run ...
  26. end run...
  27. end run...
  28. Current threading:Thread-10
  29. start run ...
  30. end run...
  31. end run...

可以看到线程 4直到 有函数结束运行end run...的时候才会开始运行,这说明我们的信号量设置成功了!

锁的示例

通过如下的示例,我们将展示上述第二个问题,线程安全的问题

  1. def muti_thread_func(func):
  2. ths = []
  3. for _ in range(10):
  4. th = func()
  5. th.start()
  6. ths.append(th)
  7. for th in ths:
  8. th.join()
  9. lock = Lock()
  10. @thread_enhance(3)
  11. def write_func():
  12. with lock:
  13. with open("lock_example.txt",'a+') as odata:
  14. odata.write("Write something...\n")

上述的muti_thread_func函数来自于之前的muti_thread_run做了一点微调,我们就可以测试不同的示例函数了,现在运行muti_thread_func(write_func)可以得到如下的lock_example.txt文件内容

  1. Write something...
  2. Write something...
  3. Write something...
  4. Write something...
  5. Write something...
  6. Write something...
  7. Write something...
  8. Write something...
  9. Write something...

其实我还写了一个不带锁的函数,但是我通过多次的测试,并没有发现结果被改乱,这个还蛮奇怪的,所以可能更好的示例还是廖雪峰老师提供的计算时混乱的示例https://www.liaoxuefeng.com/wiki/1016959663602400/1017629247922688

使用队列来实现线程间的共享

该部分的内容主要参考自python cookbook https://python3-cookbook.readthedocs.io/zh_CN/latest/c12/p03_communicating_between_threads.html#id1

如下经典的消费者和生产者的示例

  1. from queue import Queue
  2. from threading import Thread
  3. # A thread that produces data
  4. def producer(out_q):
  5. while True:
  6. # Produce some data
  7. ...
  8. out_q.put(data)
  9. # A thread that consumes data
  10. def consumer(in_q):
  11. while True:
  12. # Get some data
  13. data = in_q.get()
  14. # Process the data
  15. ...
  16. # Create the shared queue and launch both threads
  17. q = Queue()
  18. t1 = Thread(target=consumer, args=(q,))
  19. t2 = Thread(target=producer, args=(q,))
  20. t1.start()
  21. t2.start()

对象Queue已经包含了必要的锁,所以你可以通过它在多个线程间多安全地共享数据。 当使用队列时,协调生产者和消费者的关闭问题可能会有一些麻烦。一个通用的解决方法是在队列中放置一个特殊的值,当消费者读到这个值的时候,终止执行。例如:

  1. from queue import Queue
  2. from threading import Thread
  3. # Object that signals shutdown
  4. _sentinel = object()
  5. # A thread that produces data
  6. def producer(out_q):
  7. while running:
  8. # Produce some data
  9. ...
  10. out_q.put(data)
  11. # Put the sentinel on the queue to indicate completion
  12. out_q.put(_sentinel)
  13. # A thread that consumes data
  14. def consumer(in_q):
  15. while True:
  16. # Get some data
  17. data = in_q.get()
  18. # Check for termination
  19. if data is _sentinel:
  20. in_q.put(_sentinel)
  21. break
  22. # Process the data
  23. ...