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