python-从线程返回值

我如何获得一个线程以将元组或我选择的任何值返回给Python中的父级?

12个解决方案

59 votes

我建议您在启动线程之前实例化Queue.Queue,并将其作为线程的args之一传递:在线程完成之前,它.puts将其结果作为参数接收到队列中。 家长可以随意将其设置为.get或.get_nowait。

队列通常是在Python中安排线程同步和通信的最佳方法:队列本质上是线程安全的消息传递工具,这是组织多任务的最佳方法!

Alex Martelli answered 2019-11-10T12:55:40Z

12 votes

如果要调用join()等待线程完成,则只需将结果附加到Thread实例本身,然后在join()返回之后从主线程检索它。

另一方面,您没有告诉我们您打算如何发现线程已完成并且结果可用。 如果您已经有这样做的方法,它可能会为您(和我们,如果您要告诉我们)指出获得结果的最佳方法。

Peter Hansen answered 2019-11-10T12:56:14Z

12 votes

您应该将Queue实例作为参数传递,然后将返回对象.put()放入队列。 您可以通过queue.get()收集放置的任何对象的返回值。

样品:

queue = Queue.Queue()

thread_ = threading.Thread(

target=target_method,

name="Thread1",

args=[params, queue],

)

thread_.start()

thread_.join()

queue.get()

def target_method(self, params, queue):

"""

Some operations right here

"""

your_return = "Whatever your object is"

queue.put(your_return)

用于多线程:

#Start all threads in thread pool

for thread in pool:

thread.start()

response = queue.get()

thread_results.append(response)

#Kill all threads

for thread in pool:

thread.join()

我使用此实现,对我来说非常有用。 我希望你这样做。

Fatih Karatana answered 2019-11-10T12:56:55Z

7 votes

使用lambda包装目标线程函数,然后使用队列将其返回值传递回父线程。 (您的原始目标函数将保持不变,而无需额外的队列参数。)

示例代码:

import threading

import queue

def dosomething(param):

return param * 2

que = queue.Queue()

thr = threading.Thread(target = lambda q, arg : q.put(dosomething(arg)), args = (que, 2))

thr.start()

thr.join()

while not que.empty():

print(que.get())

输出:

4

Petr Vepřek answered 2019-11-10T12:57:27Z

7 votes

我很惊讶没有人提到您可以将其传递给可变对象:

>>> thread_return={'success': False}

>>> from threading import Thread

>>> def task(thread_return):

... thread_return['success'] = True

...

>>> Thread(target=task, args=(thread_return,)).start()

>>> thread_return

{'success': True}

也许这是我不知道的主要问题。

jcomeau_ictx answered 2019-11-10T12:57:59Z

5 votes

另一种方法是将回调函数传递给线程。 这提供了一种简单,安全和灵活的方式,可以随时从新线程中将值返回给父级。

# A sample implementation

import threading

import time

class MyThread(threading.Thread):

def __init__(self, cb):

threading.Thread.__init__(self)

self.callback = cb

def run(self):

for i in range(10):

self.callback(i)

time.sleep(1)

# test

import sys

def count(x):

print x

sys.stdout.flush()

t = MyThread(count)

t.start()

Vijay Mathew answered 2019-11-10T12:58:23Z

3 votes

您可以使用同步队列模块。

考虑您需要从具有已知ID的数据库中检查用户信息:

def check_infos(user_id, queue):

result = send_data(user_id)

queue.put(result)

现在,您可以像这样获取数据:

import queue, threading

queued_request = queue.Queue()

check_infos_thread = threading.Thread(target=check_infos, args=(user_id, queued_request))

check_infos_thread.start()

final_result = queued_request.get()

BoCyrill answered 2019-11-10T12:59:01Z

2 votes

POC:

import random

import threading

class myThread( threading.Thread ):

def __init__( self, arr ):

threading.Thread.__init__( self )

self.arr = arr

self.ret = None

def run( self ):

self.myJob( self.arr )

def join( self ):

threading.Thread.join( self )

return self.ret

def myJob( self, arr ):

self.ret = sorted( self.arr )

return

#Call the main method if run from the command line.

if __name__ == '__main__':

N = 100

arr = [ random.randint( 0, 100 ) for x in range( N ) ]

th = myThread( arr )

th.start( )

sortedArr = th.join( )

print "arr2: ", sortedArr

husanu answered 2019-11-10T12:59:25Z

1 votes

好吧,在Python线程模块中,有一些与锁关联的条件对象。 一种方法acquire()将返回从基础方法返回的任何值。 有关更多信息:Python条件对象

Ben Hayden answered 2019-11-10T12:59:51Z

1 votes

基于jcomeau_ictx的建议。 我遇到的最简单的一个。 此处的要求是从服务器上运行的三个不同进程获取退出状态状态,并在三个进程均成功时触发另一个脚本。 这似乎工作正常

class myThread(threading.Thread):

def __init__(self,threadID,pipePath,resDict):

threading.Thread.__init__(self)

self.threadID=threadID

self.pipePath=pipePath

self.resDict=resDict

def run(self):

print "Starting thread %s " % (self.threadID)

if not os.path.exists(self.pipePath):

os.mkfifo(self.pipePath)

pipe_fd = os.open(self.pipePath, os.O_RDWR | os.O_NONBLOCK )

with os.fdopen(pipe_fd) as pipe:

while True:

try:

message = pipe.read()

if message:

print "Received: '%s'" % message

self.resDict['success']=message

break

except:

pass

tResSer={'success':'0'}

tResWeb={'success':'0'}

tResUisvc={'success':'0'}

threads = []

pipePathSer='/tmp/path1'

pipePathWeb='/tmp/path2'

pipePathUisvc='/tmp/path3'

th1=myThread(1,pipePathSer,tResSer)

th2=myThread(2,pipePathWeb,tResWeb)

th3=myThread(3,pipePathUisvc,tResUisvc)

th1.start()

th2.start()

th3.start()

threads.append(th1)

threads.append(th2)

threads.append(th3)

for t in threads:

print t.join()

print "Res: tResSer %s tResWeb %s tResUisvc %s" % (tResSer,tResWeb,tResUisvc)

# The above statement prints updated values which can then be further processed

f-z-N answered 2019-11-10T13:00:17Z

0 votes

以下包装函数将包装现有函数并返回一个对象,该对象既指向线程(因此您可以在其上调用threading.Thread、join()等),也可以访问/查看其最终返回值。

def threadwrap(func,args,kwargs):

class res(object): result=None

def inner(*args,**kwargs):

res.result=func(*args,**kwargs)

import threading

t = threading.Thread(target=inner,args=args,kwargs=kwargs)

res.thread=t

return res

def myFun(v,debug=False):

import time

if debug: print "Debug mode ON"

time.sleep(5)

return v*2

x=threadwrap(myFun,[11],{"debug":True})

x.thread.start()

x.thread.join()

print x.result

看起来还可以,并且threading.Thread类似乎可以通过这种功能轻松扩展(*),所以我想知道为什么它还不存在。 上述方法是否有缺陷?

(*)请注意,husanu对这个问题的回答恰好做到了,将threading.Thread子类化,得到join()给出返回值的版本。

Andz answered 2019-11-10T13:01:01Z

0 votes

对于简单的程序,以上答案对我来说似乎有点过头了。 我会采纳这种可变方法:

class RetVal:

def __init__(self):

self.result = None

def threadfunc(retVal):

retVal.result = "your return value"

retVal = RetVal()

thread = Thread(target = threadfunc, args = (retVal))

thread.start()

thread.join()

print(retVal.result)

TheTrowser answered 2019-11-10T13:01:26Z

python 子线程返回值_python-从线程返回值相关推荐

  1. python中线程和进程_python中线程和进程的简单了解

    一.操作系统.应用程序 1.硬件:硬盘.cpu.主板.显卡........ 2.装系统(本身也是一个软件): 系统就是一个由程序员写出来的软件,该软件用于控制计算机得硬盘,让他们之间进行互相配合. 3 ...

  2. python异步线程算法应用_Python多线程----线程池以及线程实现异步任务

    了解异步编程 楼主在工作中遇到了以下问题,开发接口爬取数据代码完成之后要写入redis缓存,但是在写入缓存的过程花费2-3s,进行这样就大大影响了接口的性能,于是想到了使用异步存储. 传统的同步编程是 ...

  3. python os.system返回值_python os.system()返回值判断

    最近遇到os.system()执行系统命令的情况,上网搜集了一下资料,整理如下,以备不时之需,同时也希望能帮到某些人. 一.python中的 os.system(cmd)的返回值与linux命令返回值 ...

  4. python 线程池回收_python实现线程池

    这段时间一直在做一个爬虫系统,用python和django实现.其中涉及到了多线程的问题,在后端使用一个全局的字典用来保存和识别已经运行的线程.但是觉得这样的实现不是不太舒服.于是想找到一个更好的实现 ...

  5. python怎么调用函数的返回值_python函数的返回值是什么

    返回值简介 函数需要先定义后调用,函数体中 return 语句的结果就是返回值.如果一个函数没有 reutrn 语句,其实它有一个隐含的 return 语句,返回值是 None,类型也是 'NoneT ...

  6. python缺省值_python函数缺省值

    random()函数 描述:random() 方法返回随机生成的一个实数,它在[0,1)范围内.语法: import randomrandom.random(); 注意:random()是不能直接访问 ...

  7. python字典取值_python 字典中取值的两种方法小结

    python 字典中取值的两种方法小结 如下所示: a={'name':'tony','sex':'male'} 获得name的值的方式有两种 print a['name'],type(a['name ...

  8. python数组排序返回索引_python列表排序返回索引

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 我需要对列表进行排序,然后返回一个列表,其中包含列表中排序项的索引... 我有一 ...

  9. 获取python脚本的返回值_Python多线程获取返回值代码实例

    这篇文章主要介绍了Python多线程获取返回值代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在使用多线程的时候难免想要获取其操作完的返回值 ...

  10. python线程和c++线程的区别_Python、线程、吉尔和C++

    有没有办法让boost::python控制每次与python交互的python GIL?在 我正在用boost::python编写一个项目.我试图为外部库编写C++包装,并用Python脚本控制C++ ...

最新文章

  1. notepad如何新建php,notepad新手怎么使用教程
  2. python实现二叉树和它的七种遍历
  3. nodejs和Vue和Idea
  4. Java编译器API
  5. window当mac用,VirtualBox虚拟机安装os系统
  6. 使用WebBrowser自动登录阿里妈妈网站
  7. ue4 如何获取端口号_UE4编辑器开发基础
  8. 深度学习 arm linux移植过程整理
  9. 最全的测试计划模板参考
  10. ubuntu18.04 linux journalctl 命令
  11. w10计算机右键管理,Win10右键菜单怎么管理
  12. badwords.php,ucenter中词语过滤原理分析
  13. 制作“玄”字logo
  14. Jmeter把响应数据结果保存到本地文件
  15. 三国演义-(01不打不相识)
  16. 在视频中添加图片,图片中添加视频,制作画中画效果
  17. 机器学习入门 ————》 一元及多元线性回归
  18. 计算机应用基础教学计划第二学期,计算机应用基础教学计划
  19. DT时代商业革命,大数据金融行业应用发展分析
  20. 【故障分析】轴承故障分析(时频图+功率谱)含Matlab源码

热门文章

  1. 2021-01-24
  2. mybatis-plus (3.4.2)使用
  3. centos7 配置http服务器
  4. python包的init文件_Python模块包中__init__.py文件功能分析
  5. php黄页,PHP 黄页的url
  6. sqoop mysql parquet_Sqoop抽取Hive Parquet表数据到MySQL异常分析
  7. 腾讯视频怎样关闭推送迷你页面
  8. Android平台Camera2数据如何对接RTMP推流到服务器
  9. RTSP播放器开发过程中需要考虑哪些关键因素
  10. RTSP、RTMP、HTTP协议区别