python中的递归线程创建
我正在尝试实现一个递归斐波那契数列,它返回索引处的值。这是一项作业,需要使用多线程来完成。这就是我到目前为止所做的。我的问题是如何添加 live_thread1
和 live_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
I'm trying to implement a recursive Fibonacci series which returns the value at an index. It's a homework and needs to be done using multi-threading. This is what I've done so far. My question is how do I add the results from live_thread1
and live_thread2
. The threads have to be created at every level in the recursion.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
魔2024-11-24 23:39:42
您可以将可变对象传递给线程以用于存储结果。如果您不想引入新的数据类型,您可以仅使用单个元素列表:
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]
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
这是不可能的,因为您无法检索在另一个线程中执行的函数的返回值。
要实现您想要的行为,您必须使 FibonacciThreads 成为一个可调用对象,将结果存储为成员变量:
您可以像函数一样使用此类的实例:
请注意,正如我在评论中所说,这不是一个非常聪明的线程使用方式。如果这确实是你的任务,那么它就是一项糟糕的任务。
This is not possible, because you cannot retrieve the return-value of a function executed in another thread.
To implement the behavior you want, you have to make
FibonacciThreads
a callable object that stores the result as a member variable:You can use instances of this class like functions:
Note that, as I said in my comment, this is not a very smart use of threads. If this really is your assignment, it is a bad one.