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-Threading.thread returning“;无”;调用具有值的方法后_Python_Multithreading - Fatal编程技术网

Python-Threading.thread returning“;无”;调用具有值的方法后

Python-Threading.thread returning“;无”;调用具有值的方法后,python,multithreading,Python,Multithreading,所以我想做的是,我有一个循环,等等 for values in list: 每个值都有不同的列表,这很容易理解。但是我想把它和线程混为一谈。我希望每个值都应该由一个线程运行 我想向您展示我编写的代码: def get_info(thread): json_resp = json.loads(thread) #could be whatever here, Just took an example name = json_resp['name'] year = js

所以我想做的是,我有一个循环,等等

for values in list:
每个值都有不同的列表,这很容易理解。但是我想把它和线程混为一谈。我希望每个值都应该由一个线程运行

我想向您展示我编写的代码:

def get_info(thread):


    json_resp = json.loads(thread) #could be whatever here, Just took an example

    name = json_resp['name']
    year = json_resp['year']

    metadata = {
        'name': name,
        'year': year
    }

    return metadata #returning the value of metadata



def script():

    old_list = []
    new_list = [1,2,3,4,5] #Just a random new_list made.
    while True:
        for thread in new_list:
            test = threading.Thread(target=get_info, args=(thread,)).start() #Issue here

            if test in old_list:
               old_list.append(test)
我遇到的问题是,如果我像这样打印测试

for thread in new_list:
     test = threading.Thread(target=get_info, args=(thread,)).start() #Issue here
     print(test)
当它应该返回元数据时,它只是返回None


所以我想尝试做的是,for循环
for thread in new_list:
中的每个线程都是我想创建一个线程。线程稍后返回元数据的值,然后检查它是否符合
如果test in old_list:
。如果合适,它将继续,如果不合适,它应该只休眠x秒,然后重试该过程


编辑:


这里有几个问题,尽管所有问题实际上都是一个基本误解的方面

首先,
threading.Thread
实际上是一个类,因此调用
threading.Thread
生成这些类之一的实例。应将结果保存在变量中:

thr = threading.Thread(target=get_info, args=(thread,))
接下来,任何线程实例的
start
操作只需调用
run
函数。默认的
run
函数使用
args
调用您的
target
函数:

def run(self):
    """Method representing the thread's activity.

    You may override this method in a subclass. The standard run() method
    invokes the callable object passed to the object's constructor as the
    target argument, if any, with sequential and keyword arguments taken
    from the args and kwargs arguments, respectively.

    """
    try:
        if self.__target:
            self.__target(*self.__args, **self.__kwargs)
    finally:
        # Avoid a refcycle if the thread is running a function with
        # an argument that has a member that points to the thread.
        del self.__target, self.__args, self.__kwargs
请注意,
run
没有返回值,因此
start
也没有返回值

若要等待线程完成,必须调用其
join

thr.join()
这将等待线程终止(如果给定,则等待可选超时;默认情况下,等待永远)。从
run
函数返回会导致线程终止,因此如果您告诉默认
run
调用的函数返回有或没有任何返回值<代码>运行将丢弃线程终止的任何返回值

因此,最基本的问题是,您需要让您的线程将值放在其他线程(包括主程序)可以使用的地方。你可以选择放在不同的地方。处理此问题的一种方法是定义自己的类,该类派生自
threading.Thread

class Foo(threading.Thread):
    def run(self):
        self.value = get_info(...)
现在,您不需要传递
目标
参数
(如果需要,您可以这样做)。调用方可以派生多个线程:

threads=[]
# spin off five threads
for i in range(5):
    t = Foo()
    t.start()
    threads.append(t)
# now wait for all 5 threads:
for i in range(5):
    threads[i].join()
# and all our return values are now in threads[i].value

(有许多其他的方法来构造这个,但这是一个足够简单的例子。)

哦,上帝,我想说,这里有很多信息!这是非常有帮助的,但我仍然不明白到底是怎么做的,或者至少是其中的一些东西。我的意思是使用线程是一件非常复杂的事情。但是我试着像你在第一句话中所做的那样,你告诉我name to
thr=threading.Thread(target=get\u info,args=(Thread,)
,我就是这么做的,每当我打印它的时候,尽管它告诉我
,每当我试图拿回值的时候。。。我在我的帖子中编辑了我所做的。它相当复杂。线是强大的,充满锋利的边缘,就像玩杂耍运行链锯一样。:-)如果您打印一个线程实例,如
thr
,您将获得关于描述线程的类对象的信息。“stopped”(停止)表示它已完成,即,它已全部完成,
thr.join()
将立即返回。(修正-我最初说的“尚未开始”,但它显示为“初始”,而不是“停止”。)哦,是的。这真的很好,我想说,但我称之为。如果你在底部检查我的编辑。你会看到我所做的:)但我认为这种方法仍然无法从另一种方法获取信息?或者它甚至不应该从
get\u info
返回值?这里有一个术语问题:
get\u info
不是一个方法。方法是在类中定义的函数,因此对于
class Foo(threading.Thread)
,在该类中定义的函数-
def run(self):
就是方法。您的
get_info
不是一个方法,而是一个普通函数。函数只返回值;无论调用方是谁,都必须对该值进行处理。
线程
类中的默认方法会将它们丢弃,因此这些类方法显然不适合此类使用。您可以定义函数,以便将其“返回值”保存在全局变量中。但是,如果这样做,则会遇到不同的问题,即:现在有多个线程,每个线程都试图写入单个共享全局变量。你打算如何处理这个问题?(有很多方法可以做到这一点,这就是为什么线程是一个如此重要的话题。)
threads=[]
# spin off five threads
for i in range(5):
    t = Foo()
    t.start()
    threads.append(t)
# now wait for all 5 threads:
for i in range(5):
    threads[i].join()
# and all our return values are now in threads[i].value