{"id":6284,"date":"2022-12-28T23:20:28","date_gmt":"2022-12-28T23:20:28","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=6284"},"modified":"2023-06-03T14:25:32","modified_gmt":"2023-06-03T14:25:32","slug":"python-stop-thread","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-concurrency\/python-stop-thread\/","title":{"rendered":"How to Stop a Thread in Python"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to stop a thread in Python from the main thread using the Event class of the threading module.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-event-object'>Introduction to the Event object <a href=\"#introduction-to-the-event-object\" class=\"anchor\" id=\"introduction-to-the-event-object\" title=\"Anchor for Introduction to the Event object\">#<\/a><\/h2>\n\n\n\n<p>To stop a thread, you use the <code><a href=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-threading-event\/\">Event<\/a><\/code> class of the <a href=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-threading\/\">threading module<\/a>. The <code>Event<\/code> class has an internal thread-safe <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-boolean\/\">boolean<\/a> flag that can be set to <code>True<\/code> or <code>False<\/code>. By default, the internal flag is <code>False<\/code>.<\/p>\n\n\n\n<p>In the <code>Event<\/code> class, the <code>set()<\/code> method sets the internal flag to <code>True<\/code> while the <code>clear()<\/code> method resets the flag to <code>False<\/code>. Also, the <code>is_set()<\/code> method returns <code>True<\/code> if the internal flag is set to <code>True<\/code>.<\/p>\n\n\n\n<p>To stop a child thread from the main thread, you use an <code>Event <\/code>object with the following steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, create a new <code>Event<\/code> object and pass it to a child thread.<\/li>\n\n\n\n<li>Second, periodically check if the internal flag of the <code>Event<\/code> object is set in the child thread by calling the <code>is_set()<\/code> method and stop the child thread if the internal flag was set.<\/li>\n\n\n\n<li>Third, call the <code>set()<\/code> method in the main thread at some point in time to stop the child thread.<\/li>\n<\/ul>\n\n\n\n<p>The following flow chart illustrates the above steps:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/12\/python-stop-thread.png\" alt=\"python stop thread\" class=\"wp-image-6291\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id='a-simple-example-of-stopping-a-thread-in-python'>A simple example of stopping a thread in Python <a href=\"#a-simple-example-of-stopping-a-thread-in-python\" class=\"anchor\" id=\"a-simple-example-of-stopping-a-thread-in-python\" title=\"Anchor for A simple example of stopping a thread in Python\">#<\/a><\/h2>\n\n\n\n<p>The following example shows how to use an <code>Event<\/code> object to stop a child thread from the main thread:<\/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> threading <span class=\"hljs-keyword\">import<\/span> Thread, Event\n<span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> sleep\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">task<\/span><span class=\"hljs-params\">(event: Event)<\/span> -&gt; <span class=\"hljs-keyword\">None<\/span>:<\/span>\n    <span class=\"hljs-keyword\">for<\/span> i <span class=\"hljs-keyword\">in<\/span> range(<span class=\"hljs-number\">6<\/span>):\n        print(<span class=\"hljs-string\">f'Running #<span class=\"hljs-subst\">{i+<span class=\"hljs-number\">1<\/span>}<\/span>'<\/span>)\n        sleep(<span class=\"hljs-number\">1<\/span>)\n        <span class=\"hljs-keyword\">if<\/span> event.is_set():\n            print(<span class=\"hljs-string\">'The thread was stopped prematurely.'<\/span>)\n            <span class=\"hljs-keyword\">break<\/span>\n    <span class=\"hljs-keyword\">else<\/span>:\n        print(<span class=\"hljs-string\">'The thread was stopped maturely.'<\/span>)\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">()<\/span> -&gt; <span class=\"hljs-keyword\">None<\/span>:<\/span>\n\n    event = Event()\n    thread = Thread(target=task, args=(event,))\n    \n    <span class=\"hljs-comment\"># start the thread<\/span>\n    thread.start()\n\n    <span class=\"hljs-comment\"># suspend\u00a0 the thread after 3 seconds<\/span>\n    sleep(<span class=\"hljs-number\">3<\/span>)\n\n    <span class=\"hljs-comment\"># stop the child thread<\/span>\n    event.set()    \n   \n\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">'__main__'<\/span>:\n    main()<\/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<h3 class=\"wp-block-heading\" id='the-task-function'>The task() function <a href=\"#the-task-function\" class=\"anchor\" id=\"the-task-function\" title=\"Anchor for The task() function\">#<\/a><\/h3>\n\n\n\n<p>The <code>task()<\/code> function uses an <code>Event<\/code> object and returns <code>None<\/code>. It will be executed in a child thread:<\/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-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">task<\/span><span class=\"hljs-params\">(event: Event)<\/span> -&gt; <span class=\"hljs-keyword\">None<\/span>:<\/span>\n    <span class=\"hljs-keyword\">for<\/span> i <span class=\"hljs-keyword\">in<\/span> range(<span class=\"hljs-number\">6<\/span>):\n        print(<span class=\"hljs-string\">f'Running #<span class=\"hljs-subst\">{i+<span class=\"hljs-number\">1<\/span>}<\/span>'<\/span>)\n        sleep(<span class=\"hljs-number\">1<\/span>)\n        <span class=\"hljs-keyword\">if<\/span> event.is_set():\n            print(<span class=\"hljs-string\">'The thread was stopped prematurely.'<\/span>)\n            <span class=\"hljs-keyword\">break<\/span>\n    <span class=\"hljs-keyword\">else<\/span>:\n        print(<span class=\"hljs-string\">'The thread was stopped maturely.'<\/span>)<\/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>The <code>task()<\/code> function iterates over the numbers from 1 to 5. In each iteration, we use the <code>sleep()<\/code> function to delay the execution and exit the loop if the internal flag of the event object is set.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='the-main-function'>The main() function <a href=\"#the-main-function\" class=\"anchor\" id=\"the-main-function\" title=\"Anchor for The main() function\">#<\/a><\/h3>\n\n\n\n<p>First, create a new <code>Event<\/code> object:<\/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\">event = Event()<\/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>Next, create a new thread that executes the <code>task()<\/code> function with an argument as the <code>Event<\/code> object:<\/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\">thread = Thread(target=task, args=(event,))<\/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>Then, start executing the child thread:<\/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\">thread.start()<\/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>After that, suspend&nbsp;the main thread for three seconds:<\/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\">sleep(<span class=\"hljs-number\">3<\/span>)<\/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, set the internal flag of the Event object to True by calling the <code>set()<\/code> method. This will also stop the child thread:<\/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\">event.set()<\/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<h2 class=\"wp-block-heading\" id='stopping-a-thread-that-uses-a-child-class-of-the-thread-class'>Stopping a thread that uses a child class of the Thread class <a href=\"#stopping-a-thread-that-uses-a-child-class-of-the-thread-class\" class=\"anchor\" id=\"stopping-a-thread-that-uses-a-child-class-of-the-thread-class\" title=\"Anchor for Stopping a thread that uses a child class of the Thread class\">#<\/a><\/h2>\n\n\n\n<p>Sometimes, you may want to extend the <code>Thread<\/code> class and override the <code>run()<\/code> method for creating a new thread:<\/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\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">MyThread<\/span><span class=\"hljs-params\">(Thread)<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">run<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">pass<\/span><\/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>To stop the thread that uses a derived class of the <code>Thread<\/code> class, you also use the <code>Event<\/code> object of the threading module.<\/p>\n\n\n\n<p>The following example shows how to create a child thread using a derived class of the <code>Thread<\/code> class and uses the <code>Event<\/code> object to stop the child thread from the main thread in demand:<\/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, Event\n<span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> sleep\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Worker<\/span><span class=\"hljs-params\">(Thread)<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, event, *args, **kwargs)<\/span>:<\/span>\n        super().__init__(*args, **kwargs)\n        self.event = event\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">run<\/span><span class=\"hljs-params\">(self)<\/span> -&gt; <span class=\"hljs-keyword\">None<\/span>:<\/span>\n        <span class=\"hljs-keyword\">for<\/span> i <span class=\"hljs-keyword\">in<\/span> range(<span class=\"hljs-number\">6<\/span>):\n            print(<span class=\"hljs-string\">f'Running #<span class=\"hljs-subst\">{i+<span class=\"hljs-number\">1<\/span>}<\/span>'<\/span>)\n            sleep(<span class=\"hljs-number\">1<\/span>)\n            <span class=\"hljs-keyword\">if<\/span> self.event.is_set():\n                print(<span class=\"hljs-string\">'The thread was stopped prematurely.'<\/span>)\n                <span class=\"hljs-keyword\">break<\/span>\n        <span class=\"hljs-keyword\">else<\/span>:\n            print(<span class=\"hljs-string\">'The thread was stopped maturely.'<\/span>)\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">()<\/span> -&gt; <span class=\"hljs-keyword\">None<\/span>:<\/span>\n\n    <span class=\"hljs-comment\"># create a new Event object<\/span>\n    event = Event()\n\n    <span class=\"hljs-comment\"># create a new Worker thread<\/span>\n    thread = Worker(event)\n    \n    <span class=\"hljs-comment\"># start the thread<\/span>\n    thread.start()\n\n    <span class=\"hljs-comment\"># suspend\u00a0 the thread after 3 seconds<\/span>\n    sleep(<span class=\"hljs-number\">3<\/span>)\n\n    <span class=\"hljs-comment\"># stop the child thread<\/span>\n    event.set()    \n   \n\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">'__main__'<\/span>:\n    main()<\/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>How it works.<\/p>\n\n\n\n<p>First, define a <code>Worker<\/code> class that extends the <code>Thread<\/code> class from the threading module. The <code>__init__()<\/code> method of the <code>Worker<\/code> class accepts an <code>Event<\/code> object.<\/p>\n\n\n\n<p>Second, override the <code>run()<\/code> method of the <code>Worker<\/code> class and use the event object to stop the thread.<\/p>\n\n\n\n<p>Third, define the <code><code>main()<\/code><\/code> function that creates an event, a <code>Worker<\/code> thread, and passes the event object to the <code>Worker<\/code> thread. The remaining logic is the same as the <code><code>main()<\/code><\/code> function in the previous example.<\/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 <code>Event<\/code> object to stop a child thread.<\/li>\n\n\n\n<li>Use the <code>set()<\/code> method to set an internal flag of an <code>Event<\/code> object to True.<\/li>\n\n\n\n<li>Use the <code>is_set()<\/code> method to check if the internal flag of an <code>Event<\/code> object was set.<\/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=\"6284\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-stop-thread\/\"\n\t\t\t\tdata-post-title=\"How to Stop a Thread in Python\"\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=\"6284\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-stop-thread\/\"\n\t\t\t\tdata-post-title=\"How to Stop a Thread in Python\"\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 stop a thread in Python from the main thread using the Event class of the threading module.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":4104,"menu_order":9,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-6284","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/6284","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=6284"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/6284\/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=6284"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}