I want my python file to wait for all threads to close. I am using next code:
threadslist=int(threading.active_count())
while threadslist>1:
threadslist=int(threading.active_count())
print(Fore.BLUE "Scan of ports Ended in:" Style.RESET_ALL, Fore.GREEN str(round(time.time()-start_time)) Style.RESET_ALL, "s")
With that code i get this:
Scan of ports finished in 128 s
But when I put print(threadslist)
in while loop it speeds up.
Second code:
threadslist=int(threading.active_count())
while threadslist>1:
threadslist=int(threading.active_count())
print(threadslist)
print(Fore.BLUE "Scan of ports Ended in:" Style.RESET_ALL, Fore.GREEN str(round(time.time()-start_time)) Style.RESET_ALL, "s")
Now i get:
Scan of ports Ended in 26 s
Why does it take longer to finish loop without print, but not with it?
When i am not checking for threads to end, i have time of 20 s, and than 6 s for python to wait, so second time is normal.
CodePudding user response:
Busy-looping is not an efficient way to wait for threads to end. When you do that, you are using up billions of CPU cycles simply calling a function and checking its result over and over again.
Worse, in Python you are implicitly holding the GIL to do that, which means your other threads cannot run for much of the time. That is what is slowing down their execution. Adding the print statement in means that your main thread is at least doing I/O some of the time, which allows your other threads to acquire the GIL a bit more often and therefore complete more quickly.
The correct thing for your main thread to do is call join() on each of the spawned threads in sequence. That will have the same effect but not waste CPU cycles, since join() will efficiently block/sleep until the thread has exited