【问题标题】:Python: How combine returned value from 2 functions and appending them into a list using thread?Python:如何组合来自 2 个函数的返回值并使用线程将它们附加到列表中?
【发布时间】:2018-04-28 20:08:21
【问题描述】:

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

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', 'IS FUN'] ?

【问题讨论】:

标签: python multithreading concurrency threadpool python-multithreading


【解决方案1】:
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】:

    在您的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']

    【讨论】:

    • 您好,感谢您的解决方案,但是对于解决方案 1,我可以使用 1 个池而不是 2 个池吗?因为解决方案得到了 2 个 pool = pool1 和 pool2,非常感谢
    • 是的!而且它更像 Pythonic。我更新了我的答案(连同apply 示例:)
    猜你喜欢
    • 2010-11-26
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多