Welcome to a tutorial on the threading Module in Python. In Python, the threading module is used for creating, controlling, and managing threads.
The threading modules typically provide the following functions for the management of threads.
import time
import threading
def thread1(i):
time.sleep(3)
print('No. printed by Thread 1: %d' %i)
def thread2(i):
print('No. printed by Thread 2: %d' %i)
if __name__ == '__main__':
t1 = threading.Thread(target=thread1, args=(10,))
t2 = threading.Thread(target=thread2, args=(12,))
# start the threads
t1.start()
t2.start()
# join the main thread
t1.join()
t2.join()
Output:
No. printed by Thread 2: 12
No. printed by Thread 1: 10
This type of function returns the number of Thread objects currently alive.
import time
import threading
def thread1(i):
time.sleep(3)
#print('No. printed by Thread 1: %d' %i)
def thread2(i):
time.sleep(3)
#print('No. printed by Thread 2: %d' %i)
if __name__ == '__main__':
t1 = threading.Thread(target=thread1, args=(10,))
t2 = threading.Thread(target=thread2, args=(12,))
t1.start()
t2.start()
print("No. of active threads: " + threading.active_count())
t1.join()
t2.join()
Output:
No. of active threads: 3
From the above example, you will see the number of thread count to be 3, because we have created 2 threads and including the main thread in which the complete execution is occurring.
Using this function will return the current Thread object, corresponding to the caller's thread of control (that is probably in the control of the caller currently). But, if the caller's thread of control was not created through the threading module (e.g. the main thread), and a dummy thread object with limited functionality is returned.
import time
import threading
def thread1(i):
time.sleep(3)
#print('No. printed by Thread 1: %d' %i)
def thread2(i):
time.sleep(3)
#print('No. printed by Thread 2: %d' %i)
if __name__ == '__main__':
t1 = threading.Thread(target=thread1, args=(10,))
t2 = threading.Thread(target=thread2, args=(12,))
t1.start()
t2.start()
print("Current thread is: " + threading.current_thread())
t1.join()
t2.join()
Output:
Current thread is: <_MainThread(MainThread, started 16152)>
Using this function returns the thread identifier of the current thread, and it is a nonzero integer value. But, if we start the thread, then this method will return its identifier, else, it will return None.
In addition, this method can be used to index a dictionary of thread-specific data. However, thread identifiers may be recycled when a thread exits or stops and a new thread is created.
threading.get_ident()
Output:
140578859194112
With this method, a list of all the thread object currently alive is returned. It includes the daemonic threads ( i.e. if the program quits, all the daemon threads associated with it are killed automatically), dummy thread objects created by the current thread, and the main thread.
Also, the terminated threads and threads that have not yet been started are not present in this list.
threading.enumerate()
Output:
[<_MainThread(MainThread, started 139890175817472)>, <Thread(Thread-1, started 139890151225088)>, <Thread(Thread-2, started 139890142832384)>]
when used, the method returns the main Thread object. But, commonly, the main thread is the thread from which the Python interpreter was started.
threading.main_thread()
Output:
<_MainThread(MainThread, started 139890175817472)>
This method is typically used to set a trace function or hook for all the threads started by using the threadingmodule. Also, the trace function is passed to sys.settrace() method for every thread, that is attached to the thread before the run() method is called.
In the illustration below, the callback function which will act as the trace function will receive three arguments, the frame (i.e. the stack frame from the code being run), the event (i.e. a string naming the type of notification), and the arg (i.e. an event-specific value)
def hello(frame, event, arg):
print("Hello, I am a trace hook.")
threading.settrace(hello)
Now, you can attempt to update the code in the terminal at the top. So, put the hello function outside the main method and the statement threading.settrace(hello) above the statement where we call the start method for the threads.
This method is typically used to set a profile function for all threads started from the threading module. Quite like the trace function, the profile function is passed to sys.setprofile() method as well for each thread, which is attached to the thread before the call of the run() method.
threading.setprofile(hello)
This type of function returns the thread stack size used when creating new threads. Also, the size argument is optional, and can be used to set the stack size to be used for creating subsequent threads, and must be 0 or a positive integer; the D=default value is 0.
Where the changing of the thread stack size is unsupported, a RuntimeError is returned. But, when it is the specified stack size that is invalid, a ValueError is raised.
Presently, the minimum stack size supported to provide enough stack space for the interpreter is 32 KiB.
Aside, from the specified function above, the threading module defines a constant as well. Therefore, when we specify a timeout value that is greater than the value of the TIMEOUT_MAX constant, then the OverflowError error will be return
Also, aside from the functions specified above, the threading module provides many classes whose objects are very useful in creating and managing threads too.
The table below shows some of the Object types:
Object | Description |
Thread | That is an Object that represents a single thread of execution. |
Lock | The Primitive lock object. |
RLock | The RLock or Re-entrant lock object provides the ability for a single thread to (re)acquire an already-held lock (recursive locking). |
Condition | The condition variable object causes one thread to wait until a certain "condition" has been satisfied by another thread (such as a change in state or some data value) |
Event | It's a more general version of condition variables, whereby a number of threads can be made to wait for some event to occur and all the threads waiting will only awaken when the event happens. |
Semaphore | This Provides a "counter" of finite resources shared between threads block when none are available. |
BoundedSemaphore | It is similar to a Semaphore but ensures that it never exceeds its initial value. |
Timer | It is similar to Thread, except that it waits for a specified period before running. |
Barrier | This creates a "barrier" at which a specified number of threads must all arrive before they're all allowed to continue. |