{"id":1536,"date":"2023-09-27T21:27:10","date_gmt":"2023-09-27T15:57:10","guid":{"rendered":"https:\/\/geekpython.in\/?p=1536"},"modified":"2024-03-01T17:05:56","modified_gmt":"2024-03-01T11:35:56","slug":"threading-module-to-create-threads-in-python","status":"publish","type":"post","link":"https:\/\/geekpython.in\/threading-module-to-create-threads-in-python","title":{"rendered":"How to Use threading Module to Create Threads in Python"},"content":{"rendered":"\n<p>You may have heard the terms &#8220;<strong>parallelization<\/strong>&#8221; or &#8220;<strong>concurrency<\/strong>&#8220;, which refer to scheduling tasks to run parallelly or concurrently (at the same time) to save time and resources. This is a common practice in asynchronous programming, where <a href=\"https:\/\/geekpython.in\/advanced-python-coroutines-best-practices-for-efficient-asynchronous-programming\" target=\"_blank\" rel=\"noreferrer noopener\">coroutines<\/a> are used to execute tasks concurrently.<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<p class=\"responsive-video-wrap clr\"><iframe loading=\"lazy\" title=\"Python Threading in 2 Minutes: Run Multiple Tasks Concurrently | 2MinutesPy\" width=\"1200\" height=\"675\" src=\"https:\/\/www.youtube.com\/embed\/KbrUfPEwt78?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" allowfullscreen><\/iframe><\/p>\n<\/div><\/figure>\n\n\n\n<p><strong>Threading<\/strong> in Python is used to run multiple tasks at the same time, hence saving time and resources and increasing efficiency.<\/p>\n\n\n\n<p>Although multi-threading can save time and resources by executing multiple tasks at the same time, using it in code can lead to safety and reliability issues.<\/p>\n\n\n\n<p>In this article, you&#8217;ll learn what is threading in Python and how you can use it to make multiple tasks run concurrently.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is Threading?<\/h2>\n\n\n\n<p>Threading, as previously stated, refers to the concurrent execution of multiple tasks in a single process. This is accomplished by utilizing Python&#8217;s <code>threading<\/code> module.<\/p>\n\n\n\n<p>Threads are smaller units of the program that run concurrently and share the same memory space.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to Create Threads Using the threading Module<\/h2>\n\n\n\n<p>Python provides a module called <code>threading<\/code> that provides a high-level threading interface to create and manage threads in Python programs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Create and Start a Thread<\/h3>\n\n\n\n<p>A thread can be created using the <code>Thread<\/code> class provided by the <code>threading<\/code> module. Using this class, you can create an instance of the <code>Thread<\/code> and then start it using the <code>.start()<\/code> method.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:1,11-12 decode:true \">import threading\n\n# Creating Target Function\ndef num_gen(num):\n    for n in range(num):\n        print(\"Thread: \", n)\n\n# Main Code of the Program\nif __name__ == \"__main__\":\n    print(\"Statement: Creating and Starting a Thread.\")\n    thread = threading.Thread(target=num_gen, args=(3,))\n    thread.start()\n    print(\"Statement: Thread Execution Finished.\")<\/pre><\/div>\n\n\n\n<p>A thread is created by instantiating the <code>Thread<\/code> class with a <code>target<\/code> parameter that takes a callable object in this case, the <code>num_gen<\/code> function, and an <code>args<\/code> parameter that accepts a list or tuple of arguments, in this case, <code>3<\/code>.<\/p>\n\n\n\n<p>This means that you are telling <code>Thread<\/code> to run the <code>num_gen()<\/code> function and pass <code>3<\/code> as an argument.<\/p>\n\n\n\n<p>If you run the code, you&#8217;ll get the following output:<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Statement: Creating and Starting a Thread.\nStatement: Thread Execution Finished.\nThread:  0\nThread:  1\nThread:  2<\/pre><\/div>\n\n\n\n<p>You can notice that the <strong>Statement<\/strong> section of the code has finished before the <code>Thread<\/code> did. <strong>Why does this happen?<\/strong><\/p>\n\n\n\n<p>The thread starts executing concurrently with the main program and the main program does not wait for the thread to finish before continuing its execution. That&#8217;s why the above code resulted in executing the <code>print<\/code> statement before the thread was finished.<\/p>\n\n\n\n<p>To understand this, you need to understand the execution flow of the program:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, the <code>\"Statement: Creating and Starting a Thread.\"<\/code> print statement is executed.<\/li>\n\n\n\n<li>Then the thread is created and started using <code>thread.start()<\/code>.<\/li>\n\n\n\n<li>The thread starts executing concurrently with the main program.<\/li>\n\n\n\n<li>The <code>\"Statement: Thread Execution Finished.\"<\/code> print statement is executed by the main program.<\/li>\n\n\n\n<li>The thread continues and prints the output.<\/li>\n<\/ul>\n\n\n\n<p>The thread and the main program run independently that&#8217;s why their execution order is not fixed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">join() Method &#8211; The Saviour<\/h3>\n\n\n\n<p>Seeing the above situation, you might have thought then how to suspend the execution of the main program until the thread is finished executing.<\/p>\n\n\n\n<p>Well, the <code>join()<\/code> method is used in that situation, it doesn&#8217;t let e<strong>xecute the code further until the current thread terminates<\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:13 decode:true \">import threading\n\n# Creating Target Function\ndef num_gen(num):\n    for n in range(num):\n        print(\"Thread: \", n)\n\n# Main Code of the Program\nif __name__ == \"__main__\":\n    print(\"Statement: Creating and Starting a Thread.\")\n    thread = threading.Thread(target=num_gen, args=(3,))\n    thread.start()\n    thread.join()\n    print(\"Statement: Thread Execution Finished.\")<\/pre><\/div>\n\n\n\n<p>After creating and starting a thread, the <code>join()<\/code> method is called on the <code>Thread<\/code> instance (<code>thread<\/code>). Now run the code, and you&#8217;ll get the following output.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Statement: Creating and Starting a Thread.\nThread:  0\nThread:  1\nThread:  2\nStatement: Thread Execution Finished.<\/pre><\/div>\n\n\n\n<p>As can be seen, the <code>\"Statement: Thread Execution Finished.\"<\/code> print statement is executed after the thread terminates.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Daemon Threads<\/h2>\n\n\n\n<p><strong>Daemon<\/strong> threads run in the background and terminate immediately whether they completed the work or not when the main program exits.<\/p>\n\n\n\n<p>You can make a daemon thread by passing the <code>daemon<\/code> parameter when instantiating the <code>Thread<\/code> class. You can pass a boolean value to indicate whether the thread is a daemon (<code>True<\/code>) or not (<code>False<\/code>).<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:11 decode:true \">import threading\nimport time\n\ndef daemon_thread():\n    while True:\n        print(\"Daemon thread is running.\")\n        time.sleep(1)\n        print(\"Daemon thread finished executing.\")\n\nif __name__ == \"__main__\":\n    thread1 = threading.Thread(target=daemon_thread, daemon=True)\n\n    thread1.start()\n    print(\"Main program exiting.\")<\/pre><\/div>\n\n\n\n<p>A thread is created by instantiating the <code>Thread<\/code> class passing the <code>daemon_thread<\/code> function inside it and to mark it as a <strong>daemon thread<\/strong>, the <code>daemon<\/code> parameter is set to <code>True<\/code>.<\/p>\n\n\n\n<p>The <code>daemon_thread()<\/code> function is an infinite loop that prints a statement, sleeps for one second, and then again prints a statement.<\/p>\n\n\n\n<p>Now when you run the above code, you&#8217;ll get the following output.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Daemon thread is running.Main program exiting.<\/pre><\/div>\n\n\n\n<p>You can see that as soon as the main program exits, the daemon thread terminates.<\/p>\n\n\n\n<p>At the time when the <code>daemon_thread()<\/code> function enters the loop, the concurrently running main program exits, and the <code>daemon_thread()<\/code> function never reaches the next <code>print<\/code> statement as can be seen in the output.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">threading.Lock &#8211; Avoiding Race Conditions<\/h2>\n\n\n\n<p>Threads, as you know, run concurrently in a program. If your program has multiple threads, they may share the same resources or the critical section of the code at the same time, this type of condition is called <strong>race conditions<\/strong>.<\/p>\n\n\n\n<p>This is where the <code>Lock<\/code> comes into play, it acts like a synchronization barrier that prevents multiple threads from accessing the particular code or resources simultaneously.<\/p>\n\n\n\n<p>The thread calls the <code>acquire()<\/code> method to acquire the <code>Lock<\/code> and the <code>release()<\/code> method to release the <code>Lock<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:4,15,17 decode:true \">import threading\n\n# Creating Lock instance\nlock = threading.Lock()\n\ndata = \"\"\n\ndef read_file():\n    global data\n    with open(\"sample.txt\", \"r\") as file:\n        for info in file:\n            data += \"\\n\" + info\n\ndef lock_task():\n    lock.acquire()\n    read_file()\n    lock.release()\n\nif __name__ == \"__main__\":\n    thread1 = threading.Thread(target=lock_task)\n    thread2 = threading.Thread(target=lock_task)\n\n    thread1.start()\n    thread2.start()\n\n    thread1.join()\n    thread2.join()\n\n    # Printing the data read from the file\n    print(f\"Data: {data}\")<\/pre><\/div>\n\n\n\n<p>First, a <code>Lock<\/code> is created using the <code>threading.Lock()<\/code> and store it inside the <code>lock<\/code> variable.<\/p>\n\n\n\n<p>An empty string is created (<code>data<\/code>) for storing the information from both threads concurrently.<\/p>\n\n\n\n<p>The <code>read_file()<\/code> function is created that reads the information from the <code>sample.txt<\/code> file and adds it to the data.<\/p>\n\n\n\n<p>The <code>lock_task()<\/code> function is created and when it is called, the following events occur:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>lock.acquire()<\/code> method will acquire the Lock immediately when the <code>lock_task()<\/code> function is called.<\/li>\n\n\n\n<li>If the <code>Lock<\/code> is available, the program will execute the <code>read_file()<\/code> function.<\/li>\n\n\n\n<li>After the <code>read_file()<\/code> function finished executing, the <code>lock.release()<\/code> method will release the <code>Lock<\/code> to make it available again for other threads.<\/li>\n<\/ul>\n\n\n\n<p>Within the <code>if __name__ == \"__main__\"<\/code> block, two threads are created <code>thread1<\/code> and <code>thread2<\/code> that both runs the <code>lock_task()<\/code> function.<\/p>\n\n\n\n<p>Both threads run concurrently and attempt to access and execute the <code>read_file()<\/code> function at the same time but only one thread can access and enter the <code>read_file()<\/code> at a time due to the <code>Lock<\/code>.<\/p>\n\n\n\n<p>The main program waits for both threads to execute completely because of <code>thread1.join()<\/code> and <code>thread2.join()<\/code>.<\/p>\n\n\n\n<p>Then using the <code>print<\/code> statement, the information present in the file is printed.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Data: \nHello there! Welcome to GeekPython.\nHello there! Welcome to GeekPython.<\/pre><\/div>\n\n\n\n<p>As can be seen in the output, one thread at a time reads the file. However, there were two threads that&#8217;s why the file was read two times, first by <code>thread1<\/code> and then by <code>thread2<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Semaphore Objects in Threading<\/h2>\n\n\n\n<p><strong>Semaphore<\/strong> allows you to limit the number of threads that you want to access the shared resources simultaneously. Semaphore has two methods:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>acquire()<\/code>: Thread can acquire the semaphore if it is available. <strong>When a thread acquires a semaphore,<\/strong> <strong>the semaphore&#8217;s count decrement<\/strong> if it is greater than zero. If the count is zero, the thread waits until the semaphore is available.<\/li>\n\n\n\n<li><code>release()<\/code>: After using the resources, the <strong>thread releases the semaphore that results in an increment in the count<\/strong>. This means that shared resources are available.<\/li>\n<\/ul>\n\n\n\n<p>Semaphore is used to limit access to shared resources, preventing resource exhaustion and ensuring controlled access to resources with limited capacity.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:4,10,18 decode:true \">import threading\n\n# Creating a semaphore\nsem = threading.Semaphore(2)\n\ndef thread_task(num):\n    print(f\"Thread {num}: Waiting\")\n\n    # Acquire the semaphore\n    sem.acquire()\n    print(f\"Thread {num}: Acquired the semaphore\")\n\n    # Simulate some work\n    for _ in range(5):\n        print(f\"Thread {num}: In process\")\n\n    # Release the semaphore when done\n    sem.release()\n    print(f\"Thread {num}: Released the semaphore.\")\n\nif __name__ == \"__main__\":\n    thread1 = threading.Thread(target=thread_task, args=(1,))\n    thread2 = threading.Thread(target=thread_task, args=(2,))\n    thread3 = threading.Thread(target=thread_task, args=(3,))\n\n    thread1.start()\n    thread2.start()\n    thread3.start()\n\n    thread1.join()\n    thread2.join()\n    thread3.join()\n\n    print(\"All threads have finished.\")<\/pre><\/div>\n\n\n\n<p>In the above code, <code>Semaphore<\/code> is instantiated with the integer value of <code>2<\/code> which means two threads are allowed to run at the same time.<\/p>\n\n\n\n<p>Three threads are created and all of them use the <code>thread_task()<\/code> function. But only two threads are allowed to run at the same time, so two threads will access and enter the <code>thread_task()<\/code> function at the same time, and when any of the threads releases the semaphore, the third thread will acquire the semaphore.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Thread 1: Waiting\nThread 1: Acquired the semaphore\nThread 1: In process\nThread 1: In process\nThread 1: In process\nThread 1: In process\nThread 1: In processThread 2: Waiting\nThread 2: Acquired the semaphore\n\nThread 1: Released the semaphore.\nThread 2: In process\nThread 2: In process\nThread 3: WaitingThread 2: In process\nThread 3: Acquired the semaphore\nThread 3: In process\n\nThread 2: In process\nThread 2: In process\nThread 2: Released the semaphore.\nThread 3: In process\nThread 3: In process\nThread 3: In process\nThread 3: In process\nThread 3: Released the semaphore.\nAll threads have finished.<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Using ThreadPoolExecutor to Execute Tasks from a Pool of Worker Threads<\/h2>\n\n\n\n<p>The <code>ThreadPoolExecutor<\/code> is a part of <code>concurrent.features<\/code> module that is used to execute multiple tasks concurrently. Using <code>ThreadPoolExecutor<\/code>, you can run multiple tasks or functions concurrently without having to manually create and manage threads.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:1,4 decode:true \">from concurrent.futures import ThreadPoolExecutor\n\n# Creating pool of 4 threads\nexecutor = ThreadPoolExecutor(max_workers=4)\n\n# Function to evaluate square number\ndef square_num(num):\n    print(f\"Square of {num}: {num * num}.\")\n\ntask1 = executor.submit(square_num, 5)\ntask2 = executor.submit(square_num, 2)\ntask3 = executor.submit(square_num, 55)\ntask5 = executor.submit(square_num, 4)\n\n# Wait for tasks to complete and then shutdown\nexecutor.shutdown()<\/pre><\/div>\n\n\n\n<p>The above code creates a <code>ThreadPoolExecutor<\/code> with a maximum of <code>4<\/code> worker threads which means the thread pool can have a maximum of 4 worker threads executing the tasks concurrently.<\/p>\n\n\n\n<p>Four tasks are submitted to the <code>ThreadPoolExecutor<\/code> using the <code>submit<\/code> method with the <code>square_num()<\/code> function and various arguments. This will execute the function with specified arguments and prints the output.<\/p>\n\n\n\n<p>In the end, the <code>shutdown<\/code> method is called, so that <code>ThreadPoolExecutor<\/code> shutdowns after the tasks are completed and resources are freed.<\/p>\n\n\n\n<p>You don&#8217;t have to explicitly call the <code>shutdown<\/code> method if you create <code>ThreadPoolExecutor<\/code> using the <a href=\"https:\/\/geekpython.in\/context-managers-and-python-with-statement\" target=\"_blank\" rel=\"noreferrer noopener\">with statement<\/a>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:8 decode:true \">from concurrent.futures import ThreadPoolExecutor\n\n# Task\ndef square_num(num):\n    print(f\"Square of {num}: {num * num}.\")\n\n# Using ThreadPoolExecutor as context manager\nwith ThreadPoolExecutor(max_workers=4) as executor:\n    task1 = executor.submit(square_num, 5)\n    task2 = executor.submit(square_num, 2)\n    task3 = executor.submit(square_num, 55)\n    task5 = executor.submit(square_num, 4)<\/pre><\/div>\n\n\n\n<p>In the above code, the <code>ThreadPoolExecutor<\/code> is used with the <code>with<\/code> statement. When the <code>with<\/code> block is exited, the <code>ThreadPoolExecutor<\/code> is automatically shut down and its resources are released.<\/p>\n\n\n\n<p>Both codes will produce the same result.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Square of 5: 25.\nSquare of 2: 4.\nSquare of 55: 3025.\nSquare of 4: 16.<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Common Function in Threading<\/h2>\n\n\n\n<p>The <code>threading<\/code> module provides numerous functions and some of them are explained below.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Getting Main and Current Thread<\/h3>\n\n\n\n<p>The <code>threading<\/code> module has a <code>main_thread()<\/code> and a <code>current_thread()<\/code> function which is used to get the <strong>main thread<\/strong> and the <strong>currently running thread<\/strong> respectively.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:6,9,18 decode:true \">import threading\n\ndef task():\n    for _ in range(2):\n        # Getting the current thread name\n        print(f\"Current Thread: {threading.current_thread().name} is running.\")\n\n# Getting the main thread name\nprint(f\"Main thread   : {threading.main_thread().name} started.\")\nthread1 = threading.Thread(target=task)\nthread2 = threading.Thread(target=task)\n\nthread1.start()\nthread2.start()\n\nthread1.join()\nthread2.join()\nprint(f\"Main thread   : {threading.main_thread().name} finished.\")<\/pre><\/div>\n\n\n\n<p>Because the <code>main_thread()<\/code> and <code>current_thread()<\/code> functions return a <code>Thread<\/code> object, <code>threading.main_thread().name<\/code> is used to <strong>get the name of the main thread<\/strong> and <code>threading.current_thread().name<\/code> is used to <strong>get the name of the current thread<\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Main thread   : MainThread started.\nCurrent Thread: Thread-1 (task) is running.\nCurrent Thread: Thread-1 (task) is running.\nCurrent Thread: Thread-2 (task) is running.\nCurrent Thread: Thread-2 (task) is running.\nMain thread   : MainThread finished.<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Monitoring Currently Active Threads<\/h3>\n\n\n\n<p>The <code>threading.enumerate()<\/code> function is used to return the list of <code>Thread<\/code> objects that are currently running. This includes the main thread even if it is terminated and excludes terminated threads and threads that have not started yet.<\/p>\n\n\n\n<p>If you want to get the number of <code>Thread<\/code> objects that are currently alive, you can utilize the <code>threading.active_count()<\/code> function.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:16,23,26 decode:true \">import threading\n\ndef task():\n    print(f\"Current Thread     : {threading.current_thread().name} is running.\")\n\n# Getting the main thread name\nprint(f\"Main thread        : {threading.main_thread().name} started.\")\n\nthreads_list = []\n\nfor _ in range(5):\n    thread = threading.Thread(target=task)\n    thread.start()\n    threads_list.append(thread)\n    # Getting the active thread count\n    print(f\"\\nActive Thread Count: {threading.active_count()}\")\n\nfor thread in threads_list:\n    thread.join()\n\nprint(f\"Main thread        : {threading.main_thread().name} finished.\")\n# Getting the active thread count\nprint(f\"Active Thread Count: {threading.active_count()}\")\n# Getting the list of active threads\nfor active in threading.enumerate():\n    print(f\"Active Thread List: {active.name}\")<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Main thread        : MainThread started.\nCurrent Thread     : Thread-1 (task) is running.\nActive Thread Count: 2\n\nCurrent Thread     : Thread-2 (task) is running.\nActive Thread Count: 2\n\nCurrent Thread     : Thread-3 (task) is running.\nActive Thread Count: 2\n\nCurrent Thread     : Thread-4 (task) is running.\n\nActive Thread Count: 2\nCurrent Thread     : Thread-5 (task) is running.\n\nActive Thread Count: 1\nMain thread        : MainThread finished.\nActive Thread Count: 1\nActive Thread List: MainThread<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Getting Thread Id<\/h3>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:5,7 decode:true \">import threading\nimport time\n\ndef task():\n    print(f\"Thread {threading.get_ident()} is running.\")\n    time.sleep(1)\n    print(f\"Thread {threading.get_ident()} is terminated.\")\n\nprint(f\"Main thread started.\")\n\nthreads_list = []\n\nfor _ in range(5):\n    thread = threading.Thread(target=task)\n    thread.start()\n    threads_list.append(thread)\n\nfor thread in threads_list:\n    thread.join()\n\nprint(f\"Main thread finished.\")<\/pre><\/div>\n\n\n\n<p>Every thread running in a process is assigned an identifier and the <code>threading.get_ident()<\/code> function is used to retrieve the identifier of the currently running thread.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Main thread started.\nThread 9824 is running.\nThread 7188 is running.\nThread 4616 is running.\nThread 3264 is running.\nThread 7716 is running.\nThread 7716 is terminated.\nThread 9824 is terminated.\nThread 7188 is terminated.Thread 4616 is terminated.\n\nThread 3264 is terminated.\nMain thread finished.<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>A thread is a smaller unit in the program that is created using the <code>threading<\/code> module in Python. Threads are tasks or functions that you can use multiple times in your program to execute concurrently to save time and resources.<\/p>\n\n\n\n<p>In this article, you&#8217;ve learned:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>What is <strong>threading<\/strong> and how do you create and start a thread<\/li>\n\n\n\n<li>Why <code>join()<\/code> method is used<\/li>\n\n\n\n<li>What are <strong>daemon threads<\/strong> and how to create one<\/li>\n\n\n\n<li>How to Lock threads to avoid race conditions<\/li>\n\n\n\n<li>How <strong>semaphore<\/strong> is used to limit the number of threads that can access the shared resources at the same time.<\/li>\n\n\n\n<li>How you can execute a group of tasks using the <code>ThreadPoolExecutor<\/code> without having to create threads.<\/li>\n\n\n\n<li>Some common functions provided by the <code>threading<\/code> module.<\/li>\n<\/ul>\n\n\n\n<p>Reference &#8211; <a href=\"https:\/\/docs.python.org\/3\/library\/threading.html\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.python.org\/3\/library\/threading.html<\/a><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/practical-examination-of-4-deep-learning-models\">Comparing the accuracy of 4 pre-trained deep learning models<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/advanced-python-coroutines-best-practices-for-efficient-asynchronous-programming\">What are coroutines in Python and how do use them in asynchronous programming<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/asyncio-how-to-use-asyncawait-in-python\">Async\/Await in Python using the asyncio module<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/structure-flask-app-with-blueprint\">How to structure a Flask app using Flask Blueprint<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/render-images-from-flask\">Upload and display images on the frontend using Flask in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/connect-sqlite-database-with-flask-app\">How to connect the SQLite database with the Flask app using Python<\/a>?<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>You may have heard the terms &#8220;parallelization&#8221; or &#8220;concurrency&#8220;, which refer to scheduling tasks to run parallelly or concurrently (at the same time) to save time and resources. This is a common practice in asynchronous programming, where coroutines are used to execute tasks concurrently. Threading in Python is used to run multiple tasks at the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1538,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[42,2],"tags":[43,12],"class_list":["post-1536","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-modules","category-python","tag-modules","tag-python","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1536","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=1536"}],"version-history":[{"count":6,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1536\/revisions"}],"predecessor-version":[{"id":1577,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1536\/revisions\/1577"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1538"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1536"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1536"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1536"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}