Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从线程内运行的子例程中获取返回值_Python_Multithreading_Python 3.x_Python Multithreading_Subroutine - Fatal编程技术网

Python 如何从线程内运行的子例程中获取返回值

Python 如何从线程内运行的子例程中获取返回值,python,multithreading,python-3.x,python-multithreading,subroutine,Python,Multithreading,Python 3.x,Python Multithreading,Subroutine,在python 3中,我在从线程中运行的子例程中提取返回值时遇到问题 import threading from threading import Thread def dothis(): x = 17 return x Thread(target = dothis).start() print(x) 这只是给了我一个错误,说x没有定义,但我从我的子程序返回了它。有人能给我指出正确的方向吗?x是一个局部变量。它仅存在于此功能的范围内 如果希望它在函数外部可访问,则需要将

在python 3中,我在从线程中运行的子例程中提取返回值时遇到问题

import threading 
from threading import Thread 
def dothis():
    x = 17
    return x

Thread(target = dothis).start()

print(x)

这只是给了我一个错误,说x没有定义,但我从我的子程序返回了它。有人能给我指出正确的方向吗?

x
是一个局部变量。它仅存在于此功能的范围内

如果希望它在函数外部可访问,则需要将其设置为全局变量

x = 0

def dothis():
    global x
    x = 17

但是,全局变量(不是常量)通常是代码设计不佳的标志,应该避免使用,特别是对于线程,因为您可能会遇到多个线程可能试图修改同一全局变量的争用情况。

似乎您希望为函数提供输入,同时运行多个线程,并获取输出值。大概是这样的:

x = 0

def dothis():
    global x
    x = 17
import multiprocessing

def dothis(x):
    print x
    #More Code
    return x

if __name__ == '__main__':
    multiprocessing.freeze_support()
    InputsList = [1,2,3,4]
    Processors = 4
    pool = multiprocessing.Pool(Processors)
    Results = pool.map(dothis, InputsList)
    print Results
如前所述,在您的代码中,没有在函数外定义x,这就是为什么会出现此错误。输入必须在主函数中定义或定义为全局变量


您可以将输入列表传递给所需的函数,
Results
将包含返回值列表。

一个问题是您根本没有收集返回值。即使没有线程,您也必须将返回值赋给x,以便x具有值,因为x仅存在于dothis函数的作用域中。此外,由于您启动了另一个线程,您无法知道该线程是否在打印(x)之前完成执行,因为您根本没有与新线程同步。您可能应该使用队列-请参阅链接的dup问题。