質問

Pythonの親にタプルまたは自分の選択の価値を返すようにスレッドを取得するにはどうすればよいですか?

役に立ちましたか?

解決

インスタンス化することをお勧めします queue.queue スレッドを起動する前に、スレッドのargsの1つとして渡す:スレッドが終了する前に、 .puts引数として受け取ったキューの結果。親はできます .get また .get_nowait それは自由に。

キューは一般に、Pythonでスレッドの同期と通信をアレンジするための最良の方法です。それらは本質的にスレッドセーフ、メッセージパス車両です - 一般的にマルチタスクを整理するための最良の方法! - )

他のヒント

Join()を呼び出してスレッドが完了するのを待っている場合、結果をスレッドインスタンス自体に添付してから、Join()を返す後にメインスレッドから取得するだけです。

一方、スレッドが行われ、結果が利用可能であることをどのように発見するつもりなのか教えてくれません。あなたがすでにそれを行う方法を持っているなら、それはおそらくあなた(そしてあなたが私たちに言っているなら、私たちを教えてくれたなら)を指摘するでしょう。

キューインスタンスをパラメーターとして渡す必要があります。次に、.put()returnオブジェクトをキューに入れてください。 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()

私はこの実装を使用していますが、それは私にとってうまく機能します。私はあなたがそうすることを願っています。

使用する ラムダ ターゲットスレッド関数をラップし、その返品値を、 . 。 (元のターゲット関数は、追加のキューパラメーターなしで変更されていません。)

サンプルコード:

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

私はあなたがただそれを可変性に渡すことができると言ったことは誰も驚いていません:

>>> 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}

おそらく、これには私が知らない大きな問題があります。

別のアプローチは、コールバック関数をスレッドに渡すことです。これにより、新しいスレッドからいつでも、親に値を返すためのシンプルで安全で柔軟な方法が得られます。

# 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()

Synchronizedを使用できます モジュール。
既知のIDを使用してデータベースからユーザーInfosを確認する必要があると考えてください。

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()

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

さて、Pythonスレッドモジュールには、ロックに関連付けられている条件オブジェクトがあります。 1つの方法 acquire() 基礎となる方法から返される価値を返します。詳細については: Python状態オブジェクト

jcomeau_ictxの提案に基づいています。私が出会った最も簡単なもの。ここでの要件は、サーバーで実行されている3つの異なるプロセスから出口ステータスのstousを取得し、3つすべてが成功した場合に別のスクリプトをトリガーすることでした。これは正常に機能しているようです

  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

次のラッパー関数は既存の関数をラップし、両方を指すオブジェクトを返します(そうするために呼び出すことができます start(),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() 返品値を与えます。

簡単なプログラムのために、上記の答えは私にとってやり過ぎのように見えます。私は可変的なアプローチを除去します:

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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top