python多线程使用

文章目录

  • python多线程使用
    • 一、案例
    • 二、说明
      • 1、针对第一种是有返回值的 ,可以通过future.result() 去拿到每个线程返回值
      • 2、无返回值问题
      • 3、我们可以重写这个Thread类
      • 重写了__init__、run方法和join方法,主要是start()涉及的方法太多了
      • 而run()却相对简单
      • 4、重写后的run()
一、案例
def compute_ceph_func(self, i, ceph_ip)"""i:  hostinfoceph_ip: ceph_host ip """# 第一种 有返回值
def compute_ceph_port_check(self, region, ceph_ip):import concurrent.futurestmp_datas = []with concurrent.futures.ThreadPoolExecutor(max_workers=300) as executor:# 线程列表to_do = []for i in os_services:future = executor.submit(self.compute_ceph_func, i, ceph_ip)to_do.append(future)for future in concurrent.futures.as_completed(to_do):data = future.result()  # 获取每个线程的执行结果tmp_datas.extend(data)# 另外一种 无返回值
tmp_datas = []
threads = []
for i in os_services:t = threading.Thread(target=self.compute_ceph_func, args=(i, ceph_ip))threads.append(t)t.start()
for t in threads:t.join()
tmp_datas = [thread.join() for thread in threads]
logging.info(tmp_datas)# 另外一种 from concurrent.futures import ThreadPoolExecutor
from threading import Threaddef func(x):return xif __name__ == '__main__':pool = ThreadPoolExecutor(max_workers=500)li = []for i in range(1, 500):li.append(pool.submit(func, i))for l in li:print(l.result())# 关闭线程池pool.shutdown()import os
from multiprocessing.pool import ThreadPooldef func(x):print(f"Process Id:{os.getpid()} res:{x+1}", )return x + 1if __name__ == '__main__':pool = ThreadPool(processes=10)li = []for i in range(1, 500):li.append(pool.apply_async(func, args=(i,)))for p in li:print(p.get())pool.close()
二、说明
1、针对第一种是有返回值的 ,可以通过future.result() 去拿到每个线程返回值
2、无返回值问题

对于第二种方法无返回值问题:
可以重新写join方法,并且在run方法中给对象设置了一个属性,_return这个属性的值就是线程的执行结果,最后在join方法中return出来。

我们可以详细看下

# 每个线程无返回值问题
tmp_datas = []
threads = []
for i in os_services:t = threading.Thread(target=self.compute_ceph_func, args=(i, ceph_ip))threads.append(t)t.start() # start
for t in threads:t.join()
tmp_datas = [thread.join() for thread in threads]# 1、首先看start()方法def start(self):"""Start the thread's activity.It must be called at most once per thread object. It arranges for theobject's run() method to be invoked in a separate thread of control.This method will raise a RuntimeError if called more than once on thesame thread object."""if not self._initialized:raise RuntimeError("thread.__init__() not called")if self._started.is_set():raise RuntimeError("threads can only be started once")with _active_limbo_lock:_limbo[self] = selftry:_start_new_thread(self._bootstrap, ())except Exception:with _active_limbo_lock:del _limbo[self]raiseself._started.wait()
# 其实不难看出 start方法并没有返回值,并且从下面的__Init__ 中可以看出并没有存储下来class Thread:"""A class that represents a thread of control.This class can be safely subclassed in a limited fashion. There are two waysto specify the activity: by passing a callable object to the constructor, orby overriding the run() method in a subclass."""_initialized = False
# 并且从下面的__Init__ 中可以看出并没有存储下来def __init__(self, group=None, target=None, name=None,args=(), kwargs=None, *, daemon=None):"""This constructor should always be called with keyword arguments. Arguments are:*group* should be None; reserved for future extension when a ThreadGroupclass is implemented.*target* is the callable object to be invoked by the run()method. Defaults to None, meaning nothing is called.*name* is the thread name. By default, a unique name is constructed ofthe form "Thread-N" where N is a small decimal number.*args* is the argument tuple for the target invocation. Defaults to ().*kwargs* is a dictionary of keyword arguments for the targetinvocation. Defaults to {}.If a subclass overrides the constructor, it must make sure to invokethe base class constructor (Thread.__init__()) before doing anythingelse to the thread."""assert group is None, "group argument must be None for now"if kwargs is None:kwargs = {}self._target = targetself._name = str(name or _newname())self._args = argsself._kwargs = kwargsif daemon is not None:self._daemonic = daemonelse:self._daemonic = current_thread().daemonself._ident = Noneif _HAVE_THREAD_NATIVE_ID:self._native_id = Noneself._tstate_lock = Noneself._started = Event()self._is_stopped = Falseself._initialized = True# Copy of sys.stderr used by self._invoke_excepthook()self._stderr = _sys.stderrself._invoke_excepthook = _make_invoke_excepthook()# For debugging and _after_fork()_dangling.add(self)
3、我们可以重写这个Thread类
重写了__init__、run方法和join方法,主要是start()涉及的方法太多了


而run()却相对简单

4、重写后的run()

class ThreadReturnValueHanler(Thread):""""""def run(self):if self._target is not None:self._return = self._target(*self._args, **self._kwargs )def join(self):super().join()return self._return# 当然直接使用import concurrent.futures 更为方便

python多线程返回值问题重写Thread类的run方法相关推荐

  1. python多线程返回值_python获取多线程及子线程的返回值

    最近有个需求,用多线程比较合适,但是我需要每个线程的返回值,这就需要我在threading.Thread的基础上进行封装 import threading class MyThread(threadi ...

  2. Java多线程(二):Thread类

    Thread类的实例方法 start() start方法内部会调用方法start方法启动一个线程,该线程返回start方法,同时Java虚拟机调用native start0启动另一个线程调用run方法 ...

  3. Java多线程详解(深究Thread类)

    嗨喽-小伙伴们我又来了, 上一章咱介绍了线程同步,了解了解决线程安全的基本思想----"队列与锁".在前几章的介绍中,我们时不时地会使用到sleep()这个方法,知道它可以通过使线 ...

  4. python 菜鸟:返回值_Python中的真实值和虚假值:详细介绍

    python 菜鸟:返回值 欢迎 (Welcome) In this article, you will learn: 在本文中,您将学习: What truthy and falsy values ...

  5. python 函数返回值的特殊情况

    今天没事和大家一起聊聊python 函数返回值的特殊情况,之前我也碰到过类似方面的问题,到后来查阅了一些资料后,发现原来是这样! 我记得很久以前和大家聊过python列表操作方法,python列表非 ...

  6. JAVA接口返回面积_java – 将接口的返回值限制为实现类的范围

    我正在编写一个小型库,我有一些接口提供了一个返回值应该在指定范围内的方法.我如何明确禁止实现此方法的库的用户返回不在此范围内的值? 像这样的东西: //Library interface Favori ...

  7. python return返回值_Python return语句 函数返回值

    return语句是从python 函数返回一个值,在讲到定义函数的时候有讲过,每个函数都要有一个返回值.Python中的return语句有什么作用,今天就来仔细的讲解一下. python 函数返回值 ...

  8. python函数返回值的应用

    python函数返回值的应用 1.代码 def func(name,age,course):print(name,age,course)if age>22:print("too old ...

  9. Python——函数返回值

    函数返回值 如果想要获取函数中的局部变量,可以使用"return"关键字返回.例如: def foo():x = "局部变量"return xresult = ...

最新文章

  1. 芯片IP,SOC,FPGA智能卡
  2. 【Qt】Qt源码中涉及到的设计模式
  3. SPI flash配置
  4. loardrunner- 集合点函数设置
  5. [CF452E]Three strings
  6. vc通过编译指令传参_iOS开发你不知道的事编译amp;链接
  7. cdr怎样把一张图片随意变形_如何设计一张趣味的海报?
  8. Spark大数据计算引擎介绍
  9. 雨滴网易云播放器html代码,【问题求助】这种代码的播放器怎么关联网易云?...
  10. Importing the numpy c-extensions failed 解决方案
  11. 全球与中国医院电子病历系统市场深度研究分析报告
  12. 关于指令test ecx,ecx
  13. Camera ITS当中的gain/shutter组合测试
  14. Android 手机存储及路径
  15. 项目管理经典案例收集1
  16. mysql开源内库_记一次内衣渗透测试
  17. Python 获取当天日期、前一天日期、前半个月
  18. autojs遍历当前页面所有控件_纯前端表格控件SpreadJS V14.0发布:组件化编辑器+数据透视表 - 葡萄城开发工具...
  19. 字符'0'到'9'在c语言中,/0在c语言中是什么意思?
  20. Python金融学基础——夏普比率(Sharpe-ratio)和资产组合价值(portfolio-value)

热门文章

  1. 计算机基础技能都有点什么,计算机基础技能学习材料.ppt
  2. 阿里云购买云服务器流程及注意事项(新手用户必看图文教程)
  3. 数据集成解决方案探讨
  4. 冲压模具中的回弹解决办法
  5. 面试官问我new Vue阶段做了什么?
  6. Android ButterKnife(黄油刀)的使用
  7. Android第三方SDK集成 —— 极光推送
  8. hdu 6059 Kanade's trio
  9. uni-app小程序结合腾讯地图获取定位以及地图选址
  10. 1-系统C盘迁移到新买的固态硬盘SSD中有影响但不主要,但有必要将系统盘C盘迁移到新安装的 固态硬盘SSD中吗?