Python threading thread join

How to Join a Thread in Python

You can join a thread by calling the Thread.join() function.

In this tutorial you will discover how to join threads in Python.

Need to Join a Thread

A thread is a thread of execution in a computer program.

Every Python program has at least one thread of execution called the main thread. Both processes and threads are created and managed by the underlying operating system.

Sometimes we may need to create additional threads in our program in order to execute code concurrently.

Python provides the ability to create and manage new threads via the threading module and the threading.Thread class.

You can learn more about Python threads in the guude:

In concurrent programming, we may need to wait until another thread has finished running. This may be for many reasons, such as:

  • The current thread needs a result from the target thread.
  • A resource is shared between the current and target threads.
  • The current thread has no other work to complete.

The join() method provides a way for one thread to block until another thread has finished.

How can we use the join() method to join a thread in Python?

Run your loops using all CPUs, download my FREE book to learn how.

How to Join a Thread

A thread can be joined in Python by calling the Thread.join() method.

This has the effect of blocking the current thread until the target thread that has been joined has terminated.

The target thread that is being joined may terminate for a number of reasons, such as:

  • Finishes executing it’s target function.
  • Finishes executing it’s run() method if it extends the Thread class.
  • Raised an error or exception.

Once the target thread has finished, the join() method will return and the current thread can continue to execute.

The join() method requires that you have a threading.Thread instance for the thread you wish to join.

This means that if you created the thread, you may need to keep a reference to the threading.Thread instance. Alternatively, you can use the threading.enumerate() function to enumerate through all active threads and locate the thread you wish to join by name.

The join() method also takes a “timeout” argument that specifies how long the current thread is willing to wait for the target thread to terminate, in seconds.

Once the timeout has expired and the target thread has not terminated, the join() thread will return.

Источник

Читайте также:  Html text input enabled
Оцените статью