9阅网

您现在的位置是:首页 > 知识 > 正文

知识

multithreading - 在python 3中获取多线程的返回值

admin2022-10-24知识23

我试图从多线程进程中的一个线程中获取一个或几个返回值。我显示的代码得到循环,没有办法用Ctrl-C,Ctrl+D中断它。

import queue as Queue
import threading

class myThread (threading.Thread):
   def __init__(self, threadID, name, region):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.region = region
   def run(self):
      GetSales(self.region)

def GetSales(strReg): 
    print("Thread-" + strReg)
    return "Returning-" + strReg

def Main():

    RegionList = []
    RegionList.append("EMEA")
    RegionList.append("AP")
    RegionList.append("AM")

    # Create threads
    threads = []
    x = 0
    for region in RegionList:
        x += 1
        rthread = myThread(x, "Thread-" + region, region)   # Create new thread
        rthread.start()                                     # Start new thread
        threads.append(rthread)                             # Add new thread to threads list



    que = Queue.Queue()

    # Wait for all threads to complete
    for t in threads:
        t.join()
        result = que.get()
        print(t.name + " -> Done")

Main()

如果我注释 "result = que.get() "这一行,程序运行起来没有问题。



【回答】:

你要找的是未来和异步管理。

首先,你的程序循环不确定,因为行了 que.get()因为队列中没有任何东西,它在等待一些事情发生,而这些事情永远不会发生。你不要用它。


你要做的是一个异步任务并得到结果。

import asyncio

async def yourExpensiveTask():
    // some long calculation
    return 42

async main():
    tasks = []
    tasks += [asyncio.create_task(yourExpensiveTask())]
    tasks += [asyncio.create_task(yourExpensiveTask())]

    for task in tasks:
        result = await task
        print(result)

参见 https:/docs.python.org3libraryasyncio-task.html。