Recursive thread creation in python

落爺英雄遲暮 提交于 2019-12-06 21:55:38

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]

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:

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

You can use instances of this class like functions:

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!