当前位置:   article > 正文

python多线程编程,获取各个线程返回值及相关问题_multiprocessing.process 返回值

multiprocessing.process 返回值

1. multiprocessing.Process() 

针对使用multiprocessing.Process() 的多线程机制

获取返回值的方法:multiprocessing.Manager(),构造线程返回结果存储结构,本质是共享内存

具体方法样例:

  1. import os
  2. import sys
  3. import random
  4. import threading
  5. import multiprocessing
  6. # 线程执行函数
  7. def worker(procnum, return_dict):
  8. """worker function"""
  9. print(str(procnum) + " represent!")
  10. num = random.randint(5,20)
  11. arr = []
  12. for i in range(num):
  13. arr.append(i)
  14. # 依据线程id来存储各线程对应的处理结果
  15. return_dict[procnum] = (procnum,arr)
  16. if __name__ == "__main__":
  17. manager = multiprocessing.Manager()
  18. # 构造返回值存储结构,本质是共享内存方式
  19. return_dict = manager.dict()
  20. jobs = []
  21. for i in range(5):
  22. # 将构造的返回值存储结构传递给多线程执行函数,并标识各个线程id
  23. p = multiprocessing.Process(target=worker, args=(i, return_dict))
  24. jobs.append(p)
  25. p.start()
  26. for proc in jobs:
  27. proc.join()
  28. # 所有线程处理完毕后,遍历结果输出
  29. for id,arr in return_dict.values():
  30. print(id,arr)

但是,当返回数据非常大的时候,当线程执行完毕,存储结果时会报错,实验平台(vscode,centos 7).目前还没找到解决方法。

  1. Traceback (most recent call last):
  2. File "/usr/local/lib/python3.7/multiprocessing/managers.py", line 788, in _callmethod
  3. conn = self._tls.connection
  4. AttributeError: 'ForkAwareLocal' object has no attribute 'connection'
  5. During handling of the above exception, another exception occurred:
  6. Traceback (most recent call last):
  7. File "/usr/local/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap
  8. self.run()
  9. File "/usr/local/lib/python3.7/multiprocessing/process.py", line 99, in run
  10. self._target(*self._args, **self._kwargs)
  11. File "excute_fanci2.py", line 357, in product
  12. # return_dict[thread_id] = ( domains,has_word)
  13. File "<string>", line 2, in __setitem__
  14. File "/usr/local/lib/python3.7/multiprocessing/managers.py", line 792, in _callmethod
  15. self._connect()
  16. File "/usr/local/lib/python3.7/multiprocessing/managers.py", line 779, in _connect
  17. conn = self._Client(self._token.address, authkey=self._authkey)
  18. File "/usr/local/lib/python3.7/multiprocessing/connection.py", line 492, in Client
  19. c = SocketClient(address)
  20. File "/usr/local/lib/python3.7/multiprocessing/connection.py", line 619, in SocketClient
  21. s.connect(address)
  22. FileNotFoundError: [Errno 2] No such file or directory

2. multiprocessing.Pool()

使用另外一种方法 multiprocessing.Pool() ,可以解决返回数据过大问题,目前实验没有出现问题:

  1. import os
  2. import sys
  3. import random
  4. import threading
  5. import multiprocessing
  6. import time
  7. def worker(args):
  8. ## 该方法在传递多个参数时,似乎只能通过这样进行传递,否则会报错
  9. threadname, res_path, thread_id = args[0], args[1], args[2]
  10. result = [i for i in range(10000000)]
  11. return (result, thread_id)
  12. if __name__ == "__main__":
  13. process_num = 20
  14. ## 仍然是线程池方法
  15. pool = multiprocessing.Pool(processes = process_num)
  16. args_list = []
  17. ## 下面构造各个线程的参数列表,如果每个线程接受多个参数,注意在多参数接收方式
  18. for i in range(process_num):
  19. threadname = "thread"+str(i)
  20. res_path = str(i)+'_'
  21. args=(threadname,res_path,i)
  22. args_list.append(args)
  23. ## 将参数传递给线程池,绑定执行方法,map方法返回的是一个结果列表,包含各个线程的执行结果
  24. results = pool.map(worker,args_list)
  25. for result,id in results:
  26. print(results)

原文:python多线程编程,获取各个线程返回值 及 相关问题_AdvSoul的博客-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/151494?site
推荐阅读
相关标签
  

闽ICP备14008679号