日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 子线程返回值_python-从线程返回值

發布時間:2025/3/12 python 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 子线程返回值_python-从线程返回值 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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-从线程返回值的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。