I am trying to run an infinte while loop in my main thread with another parallel thread that is started and stopped/deleted in each iteration without affecting the while loop. The challenge is that the main thread must not wait for the parallel thread, i.e. it should start the next iteration regardless of whether the parallel thread in this iteration has already finished.
My main looks like that:
while true
# start iteration and do something
# start parallel thread
parallel_thread = threading.Thread(target=parallel_thread_class.thread_do_something(), daemon = True)
parallel_thread.start()
# end iteration and start new one
At the moment, the main thread (while loop) waits until the method parallel_thread_class.thread_do_something() has finished before it finishes the current iteration.
CodePudding user response:
the brackets in parallel_thread_class.thread_do_something() calls the function in the main thread, remove the brackets to have the constructed thread call the function as follows
parallel_thread = threading.Thread(target=parallel_thread_class.thread_do_something, daemon = True)
CodePudding user response:
I suggest to use asyncio. You can achieve achieve as follow:
import asyncio
async def mainTask():
i=0 #iteration counter
while True:
print('Iteration.... ',i) #prints the current iteration number
task2 = asyncio.create_task(secondTask()) #init the other task
await asyncio.sleep(2) #waits 2 secs in the main thread (you can delte this line if your iteration delays making computation)
i =1 #incremets teh counter of iterations
task2.cancel() #Cancel the task no matter if not copleted
#Your second task prints from 1 to 20 each 0.3 secs
async def secondTask():
for i in range(20):
print('Second Task: {}/20'.format(i 1))
await asyncio.sleep(0.3)
asyncio.run(mainTask())
Output:
Iteration.... 0
Second Task: 1/20
Second Task: 2/20
Second Task: 3/20
Second Task: 4/20
Second Task: 5/20
Second Task: 6/20
Second Task: 7/20
Iteration.... 1
Second Task: 1/20
Second Task: 2/20
Second Task: 3/20
Second Task: 4/20
Second Task: 5/20
Second Task: 6/20
Second Task: 7/20
Iteration.... 2
Second Task: 1/20
Second Task: 2/20
Second Task: 3/20
Second Task: 4/20
Second Task: 5/20
Second Task: 6/20
Second Task: 7/20
As you can see, the second task gets never completed and each iteration starts again
CodePudding user response:
According to python's documentation,
start()
Start the thread’s activity. It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object.
join(timeout=None)
Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.
