Python-调用具有值的方法后,Threading.thread返回“ None”

时间:2018-11-30 22:42:23

标签: 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 = 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:中的每个线程都是我要创建一个 threading.Thread ,该线程稍后将返回元数据的值,并且然后检查其是否适合if test in old_list:。如果合适,它将继续,如果不合适,则应休眠x秒钟,然后重试该过程。


编辑:

thr = threading.Thread(target=get_info, args=(thread,))
thr.start()
thr.join()
print(thr)

1 个答案:

答案 0 :(得分:1)

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

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

thr = threading.Thread(target=get_info, args=(thread,))

接下来,任何线程实例的start操作都会简单地调用run函数。默认的run函数用target调用args函数:

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调用该函数,则返回-带有或不带有任何返回值;否则,返回0。 run将丢弃任何返回值-线程终止。

那么,根本的问题是,您需要让线程将值放在其他线程(包括主程序)可以使用的位置。您可以选择将它们放置在不同的位置。解决此问题的一种方法是定义从threading.Thread派生的您自己的类

class Foo(threading.Thread):
    def run(self):
        self.value = get_info(...)

现在,您不需要传递targetargs(尽管您可以,但是也可以)。调用者可以拆分多个线程:

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

(还有许多其他方法可以构造它,但这只是一个简单的示例。)