0

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.

2
  • Your question is unclear...so please edit it and provide an minimal reproducible example — which may clarify what you're trying to do. Commented Aug 21, 2019 at 18:46
  • 1) Use a class which inherits from threading.Thread and store the results as an attribute 2) Use multiprocessing.dummy.Pools map function 3) Add the results to a list, since lists will be passed as reference. Commented Aug 21, 2019 at 18:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.