[英]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. 我有一个带有for循环的线程,我想从每个循环返回值。 But when I put return inside the loop,it break the loop permanently so I can't get other value.
但是当我将return放入循环内部时,它将永久中断循环,因此无法获得其他值。
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. 我想将此函数的
timer
用于另一个线程。
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.
将队列传递给函数(它将传递引用而不是队列的副本,这就是Python的工作原理),然后而不是返回,请使用queue.put()方法将计时器放置在队列中。 Your other thread(s) can then retrieve the value using the queue.get() method.
然后,其他线程可以使用queue.get()方法检索该值。
https://docs.python.org/3/library/queue.html https://docs.python.org/3/library/queue.html
Also is there a reason you're using not using the standard threading.Thread class? 还有使用不使用标准threading.Thread类的原因吗? It's safer to use this unless you've got some very goof reason to be using the private methods.
除非您有一些非常愚蠢的理由使用私有方法,否则使用此方法会更安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.