Python中的递归线程创建

1 投票
2 回答
2658 浏览
提问于 2025-04-16 20:43

我正在尝试实现一个递归的斐波那契数列,这个数列可以根据索引返回相应的值。这是我的作业,需要用多线程来完成。到目前为止,我已经做了这些。我的问题是,如何将live_thread1live_thread2的结果相加。在线程递归的每一层都必须创建线程。

def Recursive(n):
    if n< 2:
        return n
    else:
        return Recursive(n- 1) + Recursive(n- 2)



def FibonacciThreads(n):
    if n< 2:
        return n
    else:
        thread1        = threading.Thread(target=FibonacciThreads,args=(n-1,))
        thread2        = threading.Thread(target=FibonacciThreads,args=(n-2,))
        thread1.start()
        thread2.start()
        thread1.join()
        thread2.join()
        return live_thread1+live_thread2

2 个回答

4

这件事是不可能的,因为你无法获取在另一个线程中执行的函数的返回值。

要实现你想要的效果,你需要把 FibonacciThreads 变成一个可调用的对象,并把结果存储为一个成员变量:

class FibonacciThreads(object):
    def __init__(self):
        self.result = None

    def __call__(self, n):
        # implement logic here as above 
        # instead of a return, store the result in self.result

你可以像使用函数一样使用这个类的实例:

fib = FibonacciThreads() # create instance
fib(23) # calculate the number
print fib.result # retrieve the result

需要注意的是,正如我在评论中提到的,这并不是一个很聪明的线程使用方式。如果这真的是你的作业,那就不太好。

1

你可以把一个可变的对象传给线程,用来存储结果。如果你不想引入新的数据类型,比如说,你可以简单地使用一个只有一个元素的列表:

def fib(n, r):
    if n < 2:
        r[0] = n
    else:
        r1 = [None]
        r2 = [None]
        # Start fib() threads that use r1 and r2 for results.
        ...

        # Sum the results of the threads.
        r[0] = r1[0] + r2[0]

def FibonacciThreads(n):
    r = [None]
    fib(n, r)
    return r[0]

撰写回答