{"id":1697,"date":"2020-12-17T04:53:48","date_gmt":"2020-12-17T04:53:48","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=1697"},"modified":"2023-06-04T08:57:28","modified_gmt":"2023-06-04T08:57:28","slug":"python-threading","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-concurrency\/python-threading\/","title":{"rendered":"Python Threading"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the Python threading module to develop multi-threaded applications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='single-threaded-applications'>Single-threaded applications <a href=\"#single-threaded-applications\" class=\"anchor\" id=\"single-threaded-applications\" title=\"Anchor for Single-threaded applications\">#<\/a><\/h2>\n\n\n\n<p>Let&#8217;s start with a simple program:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> sleep, perf_counter\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">task<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n    print(<span class=\"hljs-string\">'Starting a task...'<\/span>)\n    sleep(<span class=\"hljs-number\">1<\/span>)\n    print(<span class=\"hljs-string\">'done'<\/span>)\n\n\nstart_time = perf_counter()\n\ntask()\ntask()\n\nend_time = perf_counter()\n\nprint(<span class=\"hljs-string\">f'It took <span class=\"hljs-subst\">{end_time- start_time: <span class=\"hljs-number\">0.2<\/span>f}<\/span> second(s) to complete.'<\/span>)\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, import the <code>sleep()<\/code> and <code>perf_counter()<\/code> functions from the <code>time<\/code> module:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> sleep, perf_counter<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-functions\/\">define a function<\/a> that takes one second to complete:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">task<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n    print(<span class=\"hljs-string\">'Starting a task...'<\/span>)\n    sleep(<span class=\"hljs-number\">1<\/span>)\n    print(<span class=\"hljs-string\">'done'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, get the value of the performance counter by calling the <code>perf_counter()<\/code> function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">start_time = perf_counter()       <\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Fourth, call the <code>task()<\/code> function twice:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">task()\ntask()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Fifth, get the value of the performance counter by calling the <code>perf_counter()<\/code> function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">end_time = perf_counter()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Finally, output the time that takes to complete running the <code>task()<\/code> function twice:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">print(<span class=\"hljs-string\">f'It took <span class=\"hljs-subst\">{end_time- start_time: <span class=\"hljs-number\">0.2<\/span>f}<\/span> second(s) to complete.'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Here is the output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">Starting a task...\ndone\nStarting a task...\ndone\nIt took  <span class=\"hljs-number\">2.00<\/span> second(s) to complete.<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>As you may expect, the program takes about two seconds to complete. If you call the <code>task()<\/code> function 10 times, it would take about 10 seconds to complete.<\/p>\n\n\n\n<p>The following diagram illustrates how the program works:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"544\" height=\"164\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/12\/Python-Threading-Single-threaded-App.png\" alt=\"\" class=\"wp-image-1701\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/12\/Python-Threading-Single-threaded-App.png 544w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/12\/Python-Threading-Single-threaded-App-300x90.png 300w\" sizes=\"auto, (max-width: 544px) 100vw, 544px\" \/><\/figure>\n\n\n\n<p>First, the <code>task()<\/code> function executes and sleeps for one second. Then it executes the second time and also sleeps for another second. Finally, the program completes.<\/p>\n\n\n\n<p>When the <code>task()<\/code> function calls the <code>sleep()<\/code> function, the CPU is idle. In other words, the CPU doesn&#8217;t do anything, which is not efficient in terms of resource utilization.<\/p>\n\n\n\n<p>This program has one process with a single thread, which is called the <strong>main thread<\/strong>. Because the program has only one thread, it&#8217;s called a single-threaded program.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='using-python-threading-to-develop-a-multi-threaded-program-example'>Using Python threading to develop a multi-threaded program example <a href=\"#using-python-threading-to-develop-a-multi-threaded-program-example\" class=\"anchor\" id=\"using-python-threading-to-develop-a-multi-threaded-program-example\" title=\"Anchor for Using Python threading to develop a multi-threaded program example\">#<\/a><\/h2>\n\n\n\n<p>To create a multi-threaded program, you need to use the Python <code>threading<\/code> module.<\/p>\n\n\n\n<p>First, import the <code>Thread<\/code> class from the <code>threading<\/code> module:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> threading <span class=\"hljs-keyword\">import<\/span> Thread<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, create a new thread by instantiating an instance of the <code>Thread<\/code> class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">new_thread = Thread(target=fn,args=args_tuple)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>Thread()<\/code> accepts many parameters. The main ones are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>target<\/code>: specifies a function (<code>fn<\/code>) to run in the new thread.<\/li>\n\n\n\n<li><code>args<\/code>: specifies the arguments of the function (<code>fn<\/code>). The <code>args<\/code> argument is a tuple.<\/li>\n<\/ul>\n\n\n\n<p>Third, start the thread by calling the <code>start()<\/code> method of the <code>Thread<\/code> instance:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">new_thread.start()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>If you want to wait for the thread to complete in the main thread, you can call the <code>join()<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">new_thread.join()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>By calling the <code>join()<\/code> method, the main thread will wait for the child thread to complete before it is terminated.<\/p>\n\n\n\n<p>The following program illustrates how to use the <code>threading<\/code> module:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> sleep, perf_counter\n<span class=\"hljs-keyword\">from<\/span> threading <span class=\"hljs-keyword\">import<\/span> Thread\n\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">task<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n    print(<span class=\"hljs-string\">'Starting a task...'<\/span>)\n    sleep(<span class=\"hljs-number\">1<\/span>)\n    print(<span class=\"hljs-string\">'done'<\/span>)\n\n\nstart_time = perf_counter()\n\n<span class=\"hljs-comment\"># create two new threads<\/span>\nt1 = Thread(target=task)\nt2 = Thread(target=task)\n\n<span class=\"hljs-comment\"># start the threads<\/span>\nt1.start()\nt2.start()\n\n<span class=\"hljs-comment\"># wait for the threads to complete<\/span>\nt1.join()\nt2.join()\n\nend_time = perf_counter()\n\nprint(<span class=\"hljs-string\">f'It took <span class=\"hljs-subst\">{end_time- start_time: <span class=\"hljs-number\">0.2<\/span>f}<\/span> second(s) to complete.'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works. (and we&#8217;ll focus on the threading part only)<\/p>\n\n\n\n<p>First, create two new threads:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">t1 = Thread(target=task) \nt2 = Thread(target=task)<\/code><\/span><\/pre>\n\n\n<p>Second, start both threads by calling the <code>start()<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">t1.start()\nt2.start()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, wait for both threads to complete:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">t1.join()\nt2.join()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Finally, show the executing time:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">print(<span class=\"hljs-string\">f'It took <span class=\"hljs-subst\">{end_time- start_time: <span class=\"hljs-number\">0.2<\/span>f}<\/span> second(s) to complete.'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">Starting a task...\nStarting a task...\ndone\ndone\nIt took  <span class=\"hljs-number\">1.00<\/span> second(s) to complete.<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>When the program executes, it&#8217;ll have three threads: the main thread and two other child threads.<\/p>\n\n\n\n<p>As shown clearly from the output, the program took one second instead of two to complete. <\/p>\n\n\n\n<p>The following diagram shows how threads execute:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"551\" height=\"227\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/12\/Python-Threading-Multi-threaded-App.png\" alt=\"\" class=\"wp-image-1702\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/12\/Python-Threading-Multi-threaded-App.png 551w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/12\/Python-Threading-Multi-threaded-App-300x124.png 300w\" sizes=\"auto, (max-width: 551px) 100vw, 551px\" \/><\/figure>\n<\/div>\n\n\n<h2 class=\"wp-block-heading\" id='passing-arguments-to-threads'>Passing arguments to threads <a href=\"#passing-arguments-to-threads\" class=\"anchor\" id=\"passing-arguments-to-threads\" title=\"Anchor for Passing arguments to threads\">#<\/a><\/h2>\n\n\n\n<p>The following program shows how to pass arguments to the function assigned to a thread:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> sleep, perf_counter\n<span class=\"hljs-keyword\">from<\/span> threading <span class=\"hljs-keyword\">import<\/span> Thread\n\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">task<\/span><span class=\"hljs-params\">(id)<\/span>:<\/span>\n    print(<span class=\"hljs-string\">f'Starting the task <span class=\"hljs-subst\">{id}<\/span>...'<\/span>)\n    sleep(<span class=\"hljs-number\">1<\/span>)\n    print(<span class=\"hljs-string\">f'The task <span class=\"hljs-subst\">{id}<\/span> completed'<\/span>)\n\n\nstart_time = perf_counter()\n\n<span class=\"hljs-comment\"># create and start 10 threads<\/span>\nthreads = &#91;]\n<span class=\"hljs-keyword\">for<\/span> n <span class=\"hljs-keyword\">in<\/span> range(<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">11<\/span>):\n    t = Thread(target=task, args=(n,))\n    threads.append(t)\n    t.start()\n\n<span class=\"hljs-comment\"># wait for the threads to complete<\/span>\n<span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads:\n    t.join()\n\nend_time = perf_counter()\n\nprint(<span class=\"hljs-string\">f'It took <span class=\"hljs-subst\">{end_time- start_time: <span class=\"hljs-number\">0.2<\/span>f}<\/span> second(s) to complete.'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, define a <code>task()<\/code> function that accepts an argument:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-19\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">task<\/span><span class=\"hljs-params\">(id)<\/span>:<\/span>\n    print(<span class=\"hljs-string\">f'Starting the task <span class=\"hljs-subst\">{id}<\/span>...'<\/span>)\n    sleep(<span class=\"hljs-number\">1<\/span>)\n    print(<span class=\"hljs-string\">f'The task <span class=\"hljs-subst\">{id}<\/span> completed'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, create 10 new threads and pass an id to each. The <code>threads<\/code> list is used to keep track of all newly created threads:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-20\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">threads = &#91;]\n<span class=\"hljs-keyword\">for<\/span> n <span class=\"hljs-keyword\">in<\/span> range(<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">11<\/span>):\n    t = Thread(target=task, args=(n,))\n    threads.append(t)\n    t.start()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-20\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"note\">Notice that if you call the <code>join()<\/code> method inside the loop, the program will wait for the first thread to complete before starting the next one.<\/p>\n\n\n\n<p>Third, wait for all threads to complete by calling the <code>join()<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-21\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads:\n    t.join()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-21\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The following shows the output of the program:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-22\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">Starting the task <span class=\"hljs-number\">1.<\/span>..\nStarting the task <span class=\"hljs-number\">2.<\/span>..\nStarting the task <span class=\"hljs-number\">3.<\/span>..\nStarting the task <span class=\"hljs-number\">4.<\/span>..\nStarting the task <span class=\"hljs-number\">5.<\/span>..\nStarting the task <span class=\"hljs-number\">6.<\/span>..\nStarting the task <span class=\"hljs-number\">7.<\/span>..\nStarting the task <span class=\"hljs-number\">8.<\/span>..\nStarting the task <span class=\"hljs-number\">9.<\/span>..\nStarting the task <span class=\"hljs-number\">10.<\/span>..\nThe task <span class=\"hljs-number\">10<\/span> completed\nThe task <span class=\"hljs-number\">8<\/span> completed\nThe task <span class=\"hljs-number\">1<\/span> completed\nThe task <span class=\"hljs-number\">6<\/span> completed\nThe task <span class=\"hljs-number\">7<\/span> completed\nThe task <span class=\"hljs-number\">9<\/span> completed\nThe task <span class=\"hljs-number\">3<\/span> completed\nThe task <span class=\"hljs-number\">4<\/span> completed\nThe task <span class=\"hljs-number\">2<\/span> completed\nThe task <span class=\"hljs-number\">5<\/span> completed\nIt took  <span class=\"hljs-number\">1.02<\/span> second(s) to complete.<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-22\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>It just took 1.05 seconds to complete.<\/p>\n\n\n\n<p>Notice that the program doesn&#8217;t execute the thread in the order from 1 to 10.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='when-to-use-python-threading'>When to use Python threading <a href=\"#when-to-use-python-threading\" class=\"anchor\" id=\"when-to-use-python-threading\" title=\"Anchor for When to use Python threading\">#<\/a><\/h2>\n\n\n\n<p>As introduced in the <a href=\"https:\/\/www.pythontutorial.net\/advanced-python\/differences-between-processes-and-threads\/\">process and thread tutorial<\/a>, there&#8217;re two main kinds of tasks:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>I\/O-bound tasks &#8211; the time spent on I\/O is significantly more than the time spent on computation.<\/li>\n\n\n\n<li>CPU-bound tasks &#8211; the time spent on computation is significantly higher than the time waiting for I\/O.<\/li>\n<\/ul>\n\n\n\n<p>Python threading is optimized for I\/O bound tasks. For example, requesting remote resources, connecting a database server, or reading and writing files.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='a-practical-python-threading-example'>A Practical Python threading example <a href=\"#a-practical-python-threading-example\" class=\"anchor\" id=\"a-practical-python-threading-example\" title=\"Anchor for A Practical Python threading example\">#<\/a><\/h2>\n\n\n\n<p>Suppose that you have a list of text files in a folder e.g., <code>C:\/temp\/<\/code>. And you want to replace a text with a new one in all the files.<\/p>\n\n\n\n<p>The following single-threaded program shows how to replace a substring with the new one in the text files:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-23\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> perf_counter\n\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">replace<\/span><span class=\"hljs-params\">(filename, substr, new_substr)<\/span>:<\/span>\n    print(<span class=\"hljs-string\">f'Processing the file <span class=\"hljs-subst\">{filename}<\/span>'<\/span>)\n    <span class=\"hljs-comment\"># get the contents of the file<\/span>\n    <span class=\"hljs-keyword\">with<\/span> open(filename, <span class=\"hljs-string\">'r'<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n        content = f.read()\n\n    <span class=\"hljs-comment\"># replace the substr by new_substr<\/span>\n    content = content.replace(substr, new_substr)\n\n    <span class=\"hljs-comment\"># write data into the file<\/span>\n    <span class=\"hljs-keyword\">with<\/span> open(filename, <span class=\"hljs-string\">'w'<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n        f.write(content)\n\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n    filenames = &#91;\n        <span class=\"hljs-string\">'c:\/temp\/test1.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test2.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test3.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test4.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test5.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test6.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test7.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test8.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test9.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test10.txt'<\/span>,\n    ]\n\n    <span class=\"hljs-keyword\">for<\/span> filename <span class=\"hljs-keyword\">in<\/span> filenames:\n        replace(filename, <span class=\"hljs-string\">'ids'<\/span>, <span class=\"hljs-string\">'id'<\/span>)\n\n\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">\"__main__\"<\/span>:\n    start_time = perf_counter()\n\n    main()\n\n    end_time = perf_counter()\n    print(<span class=\"hljs-string\">f'It took <span class=\"hljs-subst\">{end_time- start_time :<span class=\"hljs-number\">0.2<\/span>f}<\/span> second(s) to complete.'<\/span>)\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-23\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-24\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">It took <span class=\"hljs-number\">0.16<\/span> second(s) to complete.<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-24\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The following program has the same functionality. However, it uses multiple threads instead:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-25\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> threading <span class=\"hljs-keyword\">import<\/span> Thread\n<span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> perf_counter\n\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">replace<\/span><span class=\"hljs-params\">(filename, substr, new_substr)<\/span>:<\/span>\n    print(<span class=\"hljs-string\">f'Processing the file <span class=\"hljs-subst\">{filename}<\/span>'<\/span>)\n    <span class=\"hljs-comment\"># get the contents of the file<\/span>\n    <span class=\"hljs-keyword\">with<\/span> open(filename, <span class=\"hljs-string\">'r'<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n        content = f.read()\n\n    <span class=\"hljs-comment\"># replace the substr by new_substr<\/span>\n    content = content.replace(substr, new_substr)\n\n    <span class=\"hljs-comment\"># write data into the file<\/span>\n    <span class=\"hljs-keyword\">with<\/span> open(filename, <span class=\"hljs-string\">'w'<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n        f.write(content)\n\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n    filenames = &#91;\n        <span class=\"hljs-string\">'c:\/temp\/test1.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test2.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test3.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test4.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test5.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test6.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test7.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test8.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test9.txt'<\/span>,\n        <span class=\"hljs-string\">'c:\/temp\/test10.txt'<\/span>,\n    ]\n\n    <span class=\"hljs-comment\"># create threads<\/span>\n    threads = &#91;Thread(target=replace, args=(filename, <span class=\"hljs-string\">'id'<\/span>, <span class=\"hljs-string\">'ids'<\/span>))\n            <span class=\"hljs-keyword\">for<\/span> filename <span class=\"hljs-keyword\">in<\/span> filenames]\n\n    <span class=\"hljs-comment\"># start the threads<\/span>\n    <span class=\"hljs-keyword\">for<\/span> thread <span class=\"hljs-keyword\">in<\/span> threads:\n        thread.start()\n\n    <span class=\"hljs-comment\"># wait for the threads to complete<\/span>\n    <span class=\"hljs-keyword\">for<\/span> thread <span class=\"hljs-keyword\">in<\/span> threads:\n        thread.join()\n\n\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">\"__main__\"<\/span>:\n    start_time = perf_counter()\n\n    main()\n\n    end_time = perf_counter()\n    print(<span class=\"hljs-string\">f'It took <span class=\"hljs-subst\">{end_time- start_time :<span class=\"hljs-number\">0.2<\/span>f}<\/span> second(s) to complete.'<\/span>)\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-25\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-26\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">Processing the file c:\/temp\/test1.txt\nProcessing the file c:\/temp\/test2.txt\nProcessing the file c:\/temp\/test3.txt\nProcessing the file c:\/temp\/test4.txt\nProcessing the file c:\/temp\/test5.txt\nProcessing the file c:\/temp\/test6.txt\nProcessing the file c:\/temp\/test7.txt\nProcessing the file c:\/temp\/test8.txt\nProcessing the file c:\/temp\/test9.txt\nProcessing the file c:\/temp\/test10.txt\nIt took <span class=\"hljs-number\">0.02<\/span> second(s) to complete.<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-26\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>As you can see clearly from the output, the multi-threaded program runs so much faster.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the Python <code>threading<\/code> module to create a multi-threaded application.<\/li>\n\n\n\n<li>Use the <code>Thread(function, args)<\/code> to create a new thread.<\/li>\n\n\n\n<li>Call the <code>start()<\/code> method of the <code>Thread<\/code> class to start the thread.<\/li>\n\n\n\n<li>Call the <code>join()<\/code> method of the <code>Thread<\/code> class to wait for the thread to complete in the main thread.<\/li>\n\n\n\n<li>Only use threading for I\/O bound processing applications.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1697\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-threading\/\"\n\t\t\t\tdata-post-title=\"Python Threading\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1697\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-threading\/\"\n\t\t\t\tdata-post-title=\"Python Threading\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn how to use the Python threading module to develop multi-threaded applications.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":4104,"menu_order":1,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1697","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1697","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=1697"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1697\/revisions"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/4104"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=1697"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}