I wrote the following simple program in python:
import sys
from multiprocessing.pool import ThreadPool
def handle_ip(ip_address):
print('Child Thread')
# Visit Web Page etc...
sys.exit()
print('HI')
ip_addresses = ['1234']
pool = ThreadPool(processes=6)
p_results = [pool.apply_async(handle_ip, (ip,)) for ip in ip_addresses]
for result in p_results:
result.get()
# Wait for ALL threads to finish
print('BYE')
For some reason it never stops running (BYE
is never being printed), what's the problem?
I have 6 threads but only 1 is running as there is only one ip address in input, plus sys.exit()
terminates current thread only so after it's terminated main thread should continue and end the program.
Please Note, I want to exit only the current thread, that's why I used sys.exit()
.
My code is much more complex and this is only a simple example to show the problem (even though it doesn't make much of a sense to immediately kill the thread)
CodePudding user response:
Try calling pool.close() before your loop.
CodePudding user response:
Why you don't use concurrent?
from concurrent.futures import ThreadPoolExecutor
def handle_ip(ip_address):
print('Child Thread')
print('HI')
ip_addresses = ['1234']
with ThreadPoolExecutor(max_workers=6) as executor:
results = executor.map(handle_ip, ip_addresses)
print('BYE')