When using the thread library, Is there a way to join all threads that were created by start_new_threads ?
for example:
try:
import thread
except ImportError:
import _thread as thread #Py3K changed it.
for url in url_ip_hash.keys():
thread.start_new_thread(check_url, (url,))
How can join all threads ?
Use the Python threading module to create a multi-threaded application. Use the Thread(function, args) to create a new thread. Call the start() method of the Thread class to start the thread. Call the join() method of the Thread class to wait for the thread to complete in the main thread.
In fact, a Python process cannot run threads in parallel but it can run them concurrently through context switching during I/O bound operations. This limitation is actually enforced by GIL. The Python Global Interpreter Lock (GIL) prevents threads within the same process to be executed at the same time.
Other threads can call a thread's join() method. This blocks the calling thread until the thread whose join() method is called is terminated.
You use the join() method for that.
Is there a reason you're using thread
instead of the recommended Threading module? If not, you should rather use the threading.Thread
objects which have a join method:
from threading import Thread
def check_url(url):
# some code
threads = []
for url in url_ip_hash.keys():
t = Thread(target=check_url, args=(url, ))
t.start()
threads.append(t)
# join all threads
for t in threads:
t.join()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With