0

I'm trying to have a thread returning a value in python 3. I've been inspired by the code found here : How to get the return value from a thread in python?

I've made this working test example :

from threading import Thread
import time

def get_account_data(count, seconds=None):
    count += 1
    time.sleep(seconds)
    return count

# Call function in a thread
class ThreadWithReturn(Thread):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._return = None

    def run(self):
        target = self._target
        if not target is None:
            self._return = target(*self._args, **self._kwargs)

    def join(self, *args, **kwargs):
        super().join(*args, **kwargs)
        return self._return

def main():
    count = 0
    # Create and start thread
    thread1 = ThreadWithReturn(target=get_account_data, args=(count,), kwargs={'seconds':2})
    thread1.start()

    # Infinite loop, print count
    while(True):
        count = thread1.join()
        print (count)

if __name__ == '__main__':
    main()

The code jumps perfectly with correct parameters into get_account_data but only once. I was expecting to be called again after the time.sleep elapses.

Any clue ?

Thanks & cheers Stephane

  • Why would it be called again? – Kelly Bundy Aug 22 '21 at 19:17
  • 1
    well. I actually understand my stupid mistake. I've added a while(True) but obviously this doesn't work neither as there is a return ! So I believe to get a periodically called thread I can't use a return but I have to go through a queue – Stéphane REY Aug 23 '21 at 06:05

0 Answers0