{"id":12325,"date":"2018-12-02T17:34:30","date_gmt":"2018-12-02T12:04:30","guid":{"rendered":"http:\/\/pratikkataria.com\/blog\/?p=12325"},"modified":"2018-12-02T18:27:25","modified_gmt":"2018-12-02T12:57:25","slug":"working-with-threads-in-python","status":"publish","type":"post","link":"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/","title":{"rendered":"Working with Threads in Python"},"content":{"rendered":"<div class=\"fusion-fullwidth fullwidth-box fusion-builder-row-1 nonhundred-percent-fullwidth non-hundred-percent-height-scrolling\" style=\"background-color: #ffffff;background-position: center center;background-repeat: no-repeat;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;margin-bottom: 0px;margin-top: 0px;border-width: 0px 0px 0px 0px;border-color:#eae9e9;border-style:solid;\" ><div class=\"fusion-builder-row fusion-row\"><div class=\"fusion-layout-column fusion_builder_column fusion-builder-column-0 fusion_builder_column_1_1 1_1 fusion-one-full fusion-column-first fusion-column-last\" style=\"margin-top:0px;margin-bottom:20px;\"><div class=\"fusion-column-wrapper fusion-flex-column-wrapper-legacy\" style=\"background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;padding: 0px 0px 0px 0px;\"><div class=\"fusion-text fusion-text-1\"><h1>What is a Thread?<\/h1>\n<ul>\n<li>A thread is an active flow of control that can be activated in parallel with other threads within the same process.<\/li>\n<li>Each thread can execute a set of instructions independently and in parallel with other processes or threads.<\/li>\n<li>They share space addressing and then the data structures.<\/li>\n<li>A thread is sometimes called a lightweight process.<\/li>\n<li>The implementation of a thread is less onerous than that of a real process.<\/li>\n<li>However, unlike process, multiple threads may share many resources.<\/li>\n<\/ul>\n<h1><\/h1>\n<h1>Processes V\/S Threads<\/h1>\n<ul>\n<li>A process can consist of multiple parallel threads.<\/li>\n<li>The creation and management of a thread by the operating system is less expensive in terms of CPU&#8217;s resources than the creation and management of a process.<\/li>\n<li>Threads are used for small tasks, whereas processes are used for more heavyweight tasks.<\/li>\n<li>The threads of the same process share the address space and other resources, while processes are independent of each other.<\/li>\n<\/ul>\n<\/div><div class=\"fusion-text fusion-text-2\"><h1>Threads and Python<\/h1>\n<ul>\n<li>Thread-based parallelism is the standard way of writing parallel programs<\/li>\n<li>The python interpreter is not fully thread-safe<\/li>\n<li>In order to support multithreaded Python programs, a global lock called the Global Interpreter Lock (GIL) is used.<\/li>\n<li>Only one thread can execute the python code at the same time.<\/li>\n<li>Python automatically switches to next thread after a short period of time.<\/li>\n<li>If multiple threads attempt to access the same data object, it may end up in an inconsistent state.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from threading import Thread\r\n\r\nfrom time import sleep\r\n\r\n\r\n# To create a thread in Python, you'll want to make your class work as a thread.\r\n# For this, you should subclass your call from the Thread class\r\n\r\nclass CookBook(Thread):\r\n\r\n    def __init__(self):\r\n        Thread.__init__(self)\r\n        self.message = \"Hello parallel code!\"\r\n\r\n    # this method prints only the message\r\n    def print_message(self):\r\n        print(self.message)\r\n\r\n    # the run method prints ten times the message\r\n    def run(self):\r\n        print(\"Thread firing up\")\r\n        x = 0\r\n        while x &lt; 10:\r\n            self.print_message()\r\n            sleep(2)\r\n            x += 1\r\n        print(\"Thread Ended\\n\")\r\n\r\n\r\n# start the main process\r\nprint(\"Process started\")\r\n\r\nhello_py = CookBook()\r\n\r\nhello_py.start()\r\n\r\nprint(\"Process Ended\")\r\n<\/pre>\n<ul>\n<li>While the main program has ended, the threads continue to run every 2 seconds.<\/li>\n<li>This depicts what threads are: a subtask doing something in parent process.<\/li>\n<li>A key point is to make sure no thread keeps running in background.<\/li>\n<\/ul>\n<\/div><div class=\"fusion-clearfix\"><\/div><\/div><\/div><\/div><\/div>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":12335,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[56,212,38],"tags":[215,216,218,214,213,217],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v15.6.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Working with Threads in Python - TechAmass<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Working with Threads in Python - TechAmass\" \/>\n<meta property=\"og:url\" content=\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"TechAmass\" \/>\n<meta property=\"article:published_time\" content=\"2018-12-02T12:04:30+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2018-12-02T12:57:25+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/pratikkataria.com\/blog\/wp-content\/uploads\/2018\/12\/python-coding-programming.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1600\" \/>\n\t<meta property=\"og:image:height\" content=\"1067\" \/>\n<meta name=\"twitter:card\" content=\"summary\" \/>\n<meta name=\"twitter:creator\" content=\"@PratikPKataria\" \/>\n<meta name=\"twitter:site\" content=\"@PratikPKataria\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\">\n\t<meta name=\"twitter:data1\" content=\"3 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/pratikkataria.com\/blog\/#website\",\"url\":\"https:\/\/pratikkataria.com\/blog\/\",\"name\":\"TechAmass\",\"description\":\"Pratik&#039;s blog\",\"publisher\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/#\/schema\/person\/ef09a6ee5cb751524bc4c92454c59412\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/pratikkataria.com\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/pratikkataria.com\/blog\/wp-content\/uploads\/2018\/12\/python-coding-programming.jpg\",\"width\":1600,\"height\":1067},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/#webpage\",\"url\":\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/\",\"name\":\"Working with Threads in Python - TechAmass\",\"isPartOf\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/#primaryimage\"},\"datePublished\":\"2018-12-02T12:04:30+00:00\",\"dateModified\":\"2018-12-02T12:57:25+00:00\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/\"]}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/#webpage\"},\"author\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/#\/schema\/person\/ef09a6ee5cb751524bc4c92454c59412\"},\"headline\":\"Working with Threads in Python\",\"datePublished\":\"2018-12-02T12:04:30+00:00\",\"dateModified\":\"2018-12-02T12:57:25+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/#webpage\"},\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/#\/schema\/person\/ef09a6ee5cb751524bc4c92454c59412\"},\"image\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/#primaryimage\"},\"keywords\":\"computer,development,parallel programming,programming,python,threads\",\"articleSection\":\"Engineering,Python,Tech\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/pratikkataria.com\/blog\/working-with-threads-in-python\/#respond\"]}]},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/pratikkataria.com\/blog\/#\/schema\/person\/ef09a6ee5cb751524bc4c92454c59412\",\"name\":\"Pratik Kataria\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/pratikkataria.com\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/pratikkataria.com\/blog\/wp-content\/uploads\/2020\/02\/kpratik_sq.jpg\",\"width\":512,\"height\":512,\"caption\":\"Pratik Kataria\"},\"logo\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/#personlogo\"},\"description\":\"Pratik Kataria is currently learning Springboot and Hibernate. Technologies known and worked on: C\/C++, Java, Python, JavaScript, HTML, CSS, Wordpress, Angular, Ionic, MongoDB, SQL and Android. Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.\",\"sameAs\":[\"https:\/\/pratikkataria.com\/\"]}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","amp_enabled":true,"acf":[],"_links":{"self":[{"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/posts\/12325"}],"collection":[{"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/comments?post=12325"}],"version-history":[{"count":6,"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/posts\/12325\/revisions"}],"predecessor-version":[{"id":12331,"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/posts\/12325\/revisions\/12331"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/media\/12335"}],"wp:attachment":[{"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/media?parent=12325"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/categories?post=12325"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/tags?post=12325"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}