{"id":6602,"date":"2023-06-05T01:25:09","date_gmt":"2023-06-05T01:25:09","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=6602"},"modified":"2023-06-05T01:26:07","modified_gmt":"2023-06-05T01:26:07","slug":"python-thread-class","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-concurrency\/python-thread-class\/","title":{"rendered":"How to Extend Python Thread Class"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you will learn how to extend the Python <code>Thread<\/code> class to run code in a new thread.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-python-thread-class'>Introduction to Python Thread Class <a href=\"#introduction-to-python-thread-class\" class=\"anchor\" id=\"introduction-to-python-thread-class\" title=\"Anchor for Introduction to Python Thread Class\">#<\/a><\/h2>\n\n\n\n<p>When a Python program starts, it has a thread called the <strong>main thread<\/strong>. Sometimes, you want to offload the I\/O-bound tasks to a new thread to execute them concurrently. To do that, you use the built-in <a href=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-threading\/\">threading<\/a> module.<\/p>\n\n\n\n<p>One way to execute code in a new thread is to extend the <code>Thread<\/code> class of the <code>threading<\/code> module. Here are the steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, define a subclass of <code>threading.Thread<\/code> class.<\/li>\n\n\n\n<li>Second, override <code>__init__(self, [,args])<\/code> method inside of the <code>__init__()<\/code> method of the subclass to add custom arguments.<\/li>\n\n\n\n<li>Third, override the <code>run(self, [,args])<\/code> method inside of the subclass to customize the behavior of the new thread class when a new thread is created.<\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s take an example of extending the <code>Thread<\/code> class. We&#8217;ll develop a class that performs an HTTP request to a URL and display the response code:<\/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-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">HttpRequestThread<\/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, url: str)<\/span> -&gt; <span class=\"hljs-keyword\">None<\/span>:<\/span>\n        super().__init__()\n        self.url = url\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        print(<span class=\"hljs-string\">f'Checking <span class=\"hljs-subst\">{self.url}<\/span> ...'<\/span>)\n        <span class=\"hljs-keyword\">try<\/span>:\n            response = urllib.request.urlopen(self.url)\n            print(response.code)\n        <span class=\"hljs-keyword\">except<\/span> urllib.error.HTTPError <span class=\"hljs-keyword\">as<\/span> e:\n            print(e.code)\n        <span class=\"hljs-keyword\">except<\/span> urllib.error.URLError <span class=\"hljs-keyword\">as<\/span> e:\n            print(e.reason)<\/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, define a <code>HttpRequestThread<\/code> that extends the <code>Thread<\/code> class from the <code>threading<\/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-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">HttpRequestThread<\/span><span class=\"hljs-params\">(Thread)<\/span>:<\/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>Second, define the <code><code><code>__init__()<\/code><\/code><\/code> method that accepts a URL. Inside the <code><code><code>__init__()<\/code><\/code><\/code> method calls the <code><code><code>__init__()<\/code><\/code><\/code> method of the superclass.<\/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\">__init__<\/span><span class=\"hljs-params\">(self, url: str)<\/span> -&gt; <span class=\"hljs-keyword\">None<\/span>:<\/span>\n    super().__init__()\n    self.url = url<\/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, override the run method that uses the <code>urllib<\/code> to get the HTTP status code of the specified URL and display it to the console:<\/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\"><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    print(<span class=\"hljs-string\">f'Checking <span class=\"hljs-subst\">{self.url}<\/span> ...'<\/span>)\n    <span class=\"hljs-keyword\">try<\/span>:\n        response = urllib.request.urlopen(self.url)\n        print(response.code)\n    <span class=\"hljs-keyword\">except<\/span> urllib.error.HTTPError <span class=\"hljs-keyword\">as<\/span> e:\n        print(e.code)\n    <span class=\"hljs-keyword\">except<\/span> urllib.error.URLError <span class=\"hljs-keyword\">as<\/span> e:\n        print(e.reason)<\/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>To use the <code><code>HttpRequestThread<\/code><\/code> class, you create instances of the <code><code>HttpRequestThread<\/code><\/code> class and call the <code>start()<\/code> method. Also, you can call the <code>join()<\/code> method to wait for all the threads to complete.<\/p>\n\n\n\n<p>The following defines the <code>main()<\/code> function that uses the <code>HttpRequestThread<\/code> class:<\/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\"><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    urls = &#91;\n        <span class=\"hljs-string\">'https:\/\/httpstat.us\/200'<\/span>,\n        <span class=\"hljs-string\">'https:\/\/httpstat.us\/400'<\/span>\n    ]\n\n    threads = &#91;HttpRequestThread(url) <span class=\"hljs-keyword\">for<\/span> url <span class=\"hljs-keyword\">in<\/span> urls]\n\n    &#91;t.start() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]\n\n    &#91;t.join() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]<\/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>How it works.<\/p>\n\n\n\n<p>First, define a list of urls that we want to check:<\/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\">urls = &#91;\n    <span class=\"hljs-string\">'https:\/\/httpstat.us\/200'<\/span>,\n    <span class=\"hljs-string\">'https:\/\/httpstat.us\/400'<\/span>\n]<\/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>Second, create instances of the <code><code>HttpRequestThread<\/code><\/code> based on the <code>urls<\/code> list using list comprehension. The list comprehension returns a list of instances of the <code><code>HttpRequestThread<\/code><\/code> class:<\/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\">threads = &#91;HttpRequestThread(url) <span class=\"hljs-keyword\">for<\/span> url <span class=\"hljs-keyword\">in<\/span> urls]<\/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>Third, call the <code>start()<\/code> method of each thread in the <code>threads<\/code> list:<\/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\">&#91;t.start() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]<\/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>Finally, call the join of each <code>Thread<\/code> instance to wait for all the <code>threads<\/code> to complete:<\/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\">&#91;t.join() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]<\/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>Put it all together:<\/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\"><span class=\"hljs-keyword\">from<\/span> threading <span class=\"hljs-keyword\">import<\/span> Thread\n<span class=\"hljs-keyword\">import<\/span> urllib.request\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">HttpRequestThread<\/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, url: str)<\/span> -&gt; <span class=\"hljs-keyword\">None<\/span>:<\/span>\n        super().__init__()\n        self.url = url\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        print(<span class=\"hljs-string\">f'Checking <span class=\"hljs-subst\">{self.url}<\/span> ...'<\/span>)\n        <span class=\"hljs-keyword\">try<\/span>:\n            response = urllib.request.urlopen(self.url)\n            print(response.code)\n        <span class=\"hljs-keyword\">except<\/span> urllib.error.HTTPError <span class=\"hljs-keyword\">as<\/span> e:\n            print(e.code)\n        <span class=\"hljs-keyword\">except<\/span> urllib.error.URLError <span class=\"hljs-keyword\">as<\/span> e:\n            print(e.reason)\n\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    urls = &#91;\n        <span class=\"hljs-string\">'https:\/\/httpstat.us\/200'<\/span>,\n        <span class=\"hljs-string\">'https:\/\/httpstat.us\/400'<\/span>\n    ]\n\n    threads = &#91;HttpRequestThread(url) <span class=\"hljs-keyword\">for<\/span> url <span class=\"hljs-keyword\">in<\/span> urls]\n\n    &#91;t.start() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]\n\n    &#91;t.join() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]\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-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>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">Checking https:<span class=\"hljs-comment\">\/\/httpstat.us\/200 ...<\/span>\nChecking https:<span class=\"hljs-comment\">\/\/httpstat.us\/400 ...<\/span>\n<span class=\"hljs-number\">200<\/span>\n<span class=\"hljs-number\">400<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\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>Extend the <code>Thread<\/code> class to run code in a new thread by calling the <code>__init__()<\/code> method of the superclass in the subclass and override the run method to add the code to run in a new thread.<\/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=\"6602\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-thread-class\/\"\n\t\t\t\tdata-post-title=\"How to Extend Python Thread Class\"\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=\"6602\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-thread-class\/\"\n\t\t\t\tdata-post-title=\"How to Extend Python Thread Class\"\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 will learn how to extend the Python Thread class to run code in a new thread.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":4104,"menu_order":2,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-6602","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/6602","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=6602"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/6602\/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=6602"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}