Barry Allen
Barry Allen

Reputation: 75

Get return value from each loop of thread

I have a thread with for loop inside that I want to return the value from each loop. But when I put return inside the loop,it break the loop permanently so I can't get other value.

Here is my function:

def track_duration_count(track_length):
    time.sleep(13.2)
    for i in range(0,track_length):
        timer = str(datetime.timedelta(seconds=i))
        #sys.stdout.write(str(i)+' ')
        #sys.stdout.flush()
        return timer
        print (timer)
        time.sleep(1)
        global stop_thread
        if stop_thread:
             break
    print ("BREAKFREE")

I then call the function with:

_thread.start_new_thread(track_duration_count,(track_length,))

I want to use timer from this func for another thread.

Upvotes: 0

Views: 316

Answers (1)

Simon Notley
Simon Notley

Reputation: 2136

I'd recommend using a queue to share data between threads. Pass the queue to the function (it will pass the reference not a copy of the queue, that's how Python works) then instead of return use the queue.put() method to place timer in the queue. Your other thread(s) can then retrieve the value using the queue.get() method.

https://docs.python.org/3/library/queue.html

Also is there a reason you're using not using the standard threading.Thread class? It's safer to use this unless you've got some very goof reason to be using the private methods.

Upvotes: 1

Related Questions