代码之家  ›  专栏  ›  技术社区  ›  TYL

Python:如何组合来自2个函数的返回值,并使用线程将其附加到列表中?

  •  1
  • TYL  · 技术社区  · 7 年前

    我是线程新手,在使用线程打印列表中的值以允许两个函数同时工作并将结果附加到列表中时,我遇到了异常结果。以下是我的代码:

    import threading
    def func1():
    
      return "HTML"
    
    def func2():
    
      return "IS FUN"
    
    threadslist = []
    
    thread1 = threading.Thread(target=func1)
    thread2 = threading.Thread(target=func2)
    
    x = thread1
    y = thread2
    
    x.start()
    y.start()
    
    threadslist.append(x)
    threadslist.append(y)
    
    print(threadslist)
    

    下面是列表的结果:

    [<Thread(Thread-1, stopped 1076)>, <Thread(Thread-2, stopped 7948)>]
    

    为什么它存储Threads对象而不是存储[HTML],“很有趣”?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Sheshnath    7 年前
    import threading
    threading_list = []
    def func1():
       threading_list.append("HTML")
    
    def func2():
       threading_list.append("IS FUN")
    
    thread1 = threading.Thread(target=func1)
    thread2 = threading.Thread(target=func2)
    
    x = thread1
    y = thread2
    
    x.start()
    y.start()
    
    print(threading_list)
    
        2
  •  1
  •   Tals    7 年前

    threadlist 您正在保存线程 变量 ,这就是您在输出中看到的是它们作为字符串的表示。

    您无法获得在不同线程中运行的函数的返回值。 您可以选择:

    1. 使用 multithreading

    :

    from multiprocessing.pool import ThreadPool
    def func1():
      return 'HTML'
    
    def func2():
      return 'IS FUN'
    
    
    pool = ThreadPool(processes=1)
    
    return_values = []
    
    return_values.append(pool.apply(func1, ())) # Using apply for synchronous call directly returns the function return value.
    func2_result = pool.applyasync(func2) # Using applyasync for asynchronous call will require a later call.
    
    return_values.append(func2_result.get())  # get return value from asynchronous call to func2.
    
    print(return_values)
    
    1. 使用可变对象(如列表)保存返回值:

    :

    return_values = []
    def func1():
       return_values.append('HTML')
    
    def func2():
       return_values.append('IS FUN')
    
    # rest of your code here
    print(return_values)
    

    您将获得:

    ['HTML', 'IS FUN']