在python中创建递归线程 [英] Recursive thread creation in python
本文介绍了在python中创建递归线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试实现一个递归的斐波那契数列,该数列返回索引处的值.这是一项家庭作业,需要使用多线程来完成.到目前为止,这是我所做的.我的问题是如何添加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
推荐答案
您可以将可变对象传递给线程以用于存储结果.如果您不想引入新的数据类型,则可以例如仅使用一个元素列表:
You can pass a mutable object to the thread to use for storing the result. If you don't want to introduce a new data type, you can for example just use a single element list:
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]
这篇关于在python中创建递归线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文