简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM