{"id":6607,"date":"2023-06-05T02:22:47","date_gmt":"2023-06-05T02:22:47","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=6607"},"modified":"2023-06-05T02:28:09","modified_gmt":"2023-06-05T02:28:09","slug":"python-thread-return-value","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-concurrency\/python-thread-return-value\/","title":{"rendered":"How to Return Values from a Thread"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you will learn how to return values from a child thread to the main thread by extending the <code>threading.Thread<\/code> class.<\/p>\n\n\n\n<p>When a Python program starts, it has a single thread called the <strong>main thread<\/strong>. Sometimes, you want to offload I\/O tasks to new <a href=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-threading\/\">threads<\/a> and execute them concurrently. Additionally, you may also want to get the return values from these threads from the main thread.<\/p>\n\n\n\n<p>To return a value from a thread, you can <a href=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-thread-class\/\">extend the Thread class<\/a> and store that value in the instance of the class.<\/p>\n\n\n\n<p>The following example illustrates how to check a specified URL and return its HTTP status code in a separate 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\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        self.http_status_code = <span class=\"hljs-literal\">None<\/span>\n        self.reason = <span class=\"hljs-literal\">None<\/span>\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\">try<\/span>:\n            response = urllib.request.urlopen(self.url)\n            self.http_status_code = response.code\n        <span class=\"hljs-keyword\">except<\/span> urllib.error.HTTPError <span class=\"hljs-keyword\">as<\/span> e:\n            self.http_status_code = e.code\n        <span class=\"hljs-keyword\">except<\/span> urllib.error.URLError <span class=\"hljs-keyword\">as<\/span> e:\n            self.reason = 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    <span class=\"hljs-comment\"># create new threads<\/span>\n    threads = &#91;HttpRequestThread(url) <span class=\"hljs-keyword\">for<\/span> url <span class=\"hljs-keyword\">in<\/span> urls]\n\n    <span class=\"hljs-comment\"># start the threads<\/span>\n    &#91;t.start() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]\n\n    <span class=\"hljs-comment\"># wait for the threads to complete<\/span>\n    &#91;t.join() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]\n\n    <span class=\"hljs-comment\"># display the URLs with HTTP status codes<\/span>\n    &#91;print(<span class=\"hljs-string\">f'<span class=\"hljs-subst\">{t.url}<\/span>: <span class=\"hljs-subst\">{t.http_status_code}<\/span>'<\/span>) <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()\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    <span class=\"hljs-comment\"># create new threads<\/span>\n    threads = &#91;HttpRequestThread(url) <span class=\"hljs-keyword\">for<\/span> url <span class=\"hljs-keyword\">in<\/span> urls]\n\n    <span class=\"hljs-comment\"># start the threads<\/span>\n    &#91;t.start() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]\n\n    <span class=\"hljs-comment\"># wait for the threads to complete<\/span>\n    &#91;t.join() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]\n\n    <span class=\"hljs-comment\"># display the URLs with HTTP status codes<\/span>\n    &#91;print(<span class=\"hljs-string\">f'<span class=\"hljs-subst\">{t.url}<\/span>: <span class=\"hljs-subst\">{t.http_status_code}<\/span>'<\/span>) <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]\n\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>Output:<\/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\">ttps:\/\/httpstat.us\/<span class=\"hljs-number\">200<\/span>: <span class=\"hljs-number\">200<\/span>\nhttps:\/\/httpstat.us\/<span class=\"hljs-number\">400<\/span>: <span class=\"hljs-number\">400<\/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>How it works.<\/p>\n\n\n\n<p>First, define the <code>HttpRequestThread<\/code> class that extends the <code>Thread<\/code> class:<\/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-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">HttpRequestThread<\/span><span class=\"hljs-params\">(Thread)<\/span>:<\/span>\n<span class=\"hljs-comment\"># ...<\/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>Second, define the <code><code>__init__()<\/code><\/code> method that accepts a URL. Inside the <code><code>__init__()<\/code><\/code> method adds <code>url<\/code>, <code><code>http_status_code<\/code><\/code>, and <code>reason<\/code> instance variables. The <code><code>http_status_code<\/code><\/code> will store the status code of the <code>url<\/code> at the time of checking and the <code>reason<\/code> will store the error message in case an error occurs:<\/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\">__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    self.http_status_code = <span class=\"hljs-literal\">None<\/span>\n    self.reason = <span class=\"hljs-literal\">None<\/span><\/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>Third, override the <code>run()<\/code> method that uses the <code>urllib<\/code> library to get the HTTP status code of the specified URL and assigns it to <code>http_status_code<\/code> field. If an error occurs, it assigns the error message to the <code>reason<\/code> field: <\/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\">run<\/span><span class=\"hljs-params\">(self)<\/span> -&gt; <span class=\"hljs-keyword\">None<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        response = urllib.request.urlopen(self.url)\n        self.http_status_code = response.code\n    <span class=\"hljs-keyword\">except<\/span> urllib.error.HTTPError <span class=\"hljs-keyword\">as<\/span> e:\n        self.http_status_code = e.code\n    <span class=\"hljs-keyword\">except<\/span> urllib.error.URLError <span class=\"hljs-keyword\">as<\/span> e:\n        self.reason = e.reason<\/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>Later, we can access the <code>url<\/code>, <code>http_status_code<\/code>, and <code>reason<\/code> from the instance of the <code>HttpRequestThread<\/code> class.<\/p>\n\n\n\n<p>Fourth, define the <code>main()<\/code> function that creates instances of the <code>HttpRequestThread<\/code> class, start the threads, wait for them to complete, and get the result from the instances:<\/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\"><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    <span class=\"hljs-comment\"># create new threads<\/span>\n    threads = &#91;HttpRequestThread(url) <span class=\"hljs-keyword\">for<\/span> url <span class=\"hljs-keyword\">in<\/span> urls]\n\n    <span class=\"hljs-comment\"># start the threads<\/span>\n    &#91;t.start() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]\n\n    <span class=\"hljs-comment\"># wait for the threads to complete<\/span>\n    &#91;t.join() <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]\n\n    <span class=\"hljs-comment\"># display the URLs with HTTP status codes<\/span>\n    &#91;print(<span class=\"hljs-string\">f'<span class=\"hljs-subst\">{t.url}<\/span>: <span class=\"hljs-subst\">{t.http_status_code}<\/span>'<\/span>) <span class=\"hljs-keyword\">for<\/span> t <span class=\"hljs-keyword\">in<\/span> threads]<\/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<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 and set the instance variables inside the subclass to return the values from a child thread to the main 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=\"6607\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-thread-return-value\/\"\n\t\t\t\tdata-post-title=\"How to Return Values from a Thread\"\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=\"6607\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-thread-return-value\/\"\n\t\t\t\tdata-post-title=\"How to Return Values from a Thread\"\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 return values from a child thread to the main thread by extending the threading.Thread class.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":4104,"menu_order":3,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-6607","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/6607","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=6607"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/6607\/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=6607"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}