{"id":12344,"date":"2018-12-02T22:53:05","date_gmt":"2018-12-02T17:23:05","guid":{"rendered":"http:\/\/pratikkataria.com\/blog\/?p=12344"},"modified":"2018-12-02T23:46:11","modified_gmt":"2018-12-02T18:16:11","slug":"thread-synchronization-with-lock-in-python","status":"publish","type":"post","link":"https:\/\/pratikkataria.com\/blog\/thread-synchronization-with-lock-in-python\/","title":{"rendered":"Thread Synchronization with Lock 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\"><h2>Why Lock() ?<\/h2>\n<ul>\n<li>When 2 or more operations belonging to concurrent threads try to access the shared memory, a race condition can occur<\/li>\n<li>The easiest way to get around the race conditions is the use of a lock<\/li>\n<li>The operation of a lock is simple when a thread wants to access a portion of shared memory, it must necessarily acquire a lock on that portion prior to using it.<\/li>\n<li>After completing its operation, the thread must release the lock that was previously obtained.<\/li>\n<li>The impossibility of incurring races is critical as the need of the lock for the thread.<\/li>\n<\/ul>\n<h2>Deadlock<\/h2>\n<ul>\n<li>A deadlock occurs due to the acquisition of a lock from different threads<\/li>\n<li>It is impossible to proceed with the execution of operations<\/li>\n<\/ul>\n<h2>Advantages of Lock()<\/h2>\n<ul>\n<li>It allows us to restrict the access of a shared resource to a single thread or a single type of thread at a time<\/li>\n<li>Before accessing the shared resource of the program, the thread must acquire the lock and must then allow any other threads access to the same resource.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">import threading\r\n\r\nshared_resource_with_lock = 0\r\n\r\nshared_resource_with_no_lock = 0\r\n\r\nCOUNT = 10000\r\n\r\nshared_resource_lock = threading.Lock()\r\n\r\n# Lock Management\r\n\r\ndef increment_with_lock():\r\n    global shared_resource_with_lock\r\n    for i in range(COUNT):\r\n        shared_resource_lock.acquire()\r\n        shared_resource_with_lock += 1\r\n        shared_resource_lock.release()\r\n\r\ndef decrement_with_lock():\r\n    global shared_resource_with_lock\r\n    for i in range(COUNT):\r\n        shared_resource_lock.acquire()\r\n        shared_resource_with_lock -= 1\r\n        shared_resource_lock.release()\r\n\r\ndef increment_without_lock():\r\n    global shared_resource_with_no_lock\r\n    for i in range(COUNT):\r\n        shared_resource_with_no_lock += 1\r\n\r\ndef decrement_without_lock():\r\n    global shared_resource_with_no_lock\r\n    for i in range(COUNT):\r\n        shared_resource_with_no_lock -= 1\r\n\r\nif __name__ == \"__main__\":\r\n    t1 = threading.Thread(target = increment_with_lock)\r\n    t2 = threading.Thread(target = decrement_with_lock)\r\n    t3 = threading.Thread(target = increment_without_lock)\r\n    t4 = threading.Thread(target = decrement_without_lock)\r\n\r\n    t1.start()\r\n    t2.start()\r\n    t3.start()\r\n    t4.start()\r\n    t1.join()\r\n    t2.join()\r\n    t3.join()\r\n    t4.join()\r\n\r\n    print(\"the value of shared variable with lock management is %s\"\\\r\n          %shared_resource_with_lock\r\n          )\r\n\r\n    print(\"the value of shared variable with race condition is %s\" \\\r\n          %shared_resource_with_no_lock)<\/pre>\n<ul>\n<li>Locks have two states: Locked and unlocked<\/li>\n<li>We have two methods that are used to manipulate the locks: acquire() and release()<\/li>\n<\/ul>\n<h2>Rules<\/h2>\n<ul>\n<li>If the state is unlocked, a call to acquire() changes state to locked<\/li>\n<li>If the state is locked, a call to acquire() blocks until another thread calls release()<\/li>\n<li>If the state is unlocked, a call to release() raises a Runtime Error exception<\/li>\n<li>If the state is locked, a call to release() changes the state to unlocked<\/li>\n<\/ul>\n<h2>Disadvantages<\/h2>\n<ul>\n<li>The locks are subject to harmful situations of deadlock<\/li>\n<li>They have many other negative aspects for the application as a whole<\/li>\n<li>It also limits the scalability of the code and its readability<\/li>\n<li>The use of a lock is in conflict with the possible need to impose the priority of access to the memory shared by the various processes<\/li>\n<li>An application containing a lock presents considerable difficulties when searching for errors or debugging<\/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":[212,38],"tags":[283,308,218,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>Thread Synchronization with Lock 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\/thread-synchronization-with-lock-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Thread Synchronization with Lock in Python - TechAmass\" \/>\n<meta property=\"og:url\" content=\"https:\/\/pratikkataria.com\/blog\/thread-synchronization-with-lock-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"TechAmass\" \/>\n<meta property=\"article:published_time\" content=\"2018-12-02T17:23:05+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2018-12-02T18:16:11+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=\"4 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\/thread-synchronization-with-lock-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\/thread-synchronization-with-lock-in-python\/#webpage\",\"url\":\"https:\/\/pratikkataria.com\/blog\/thread-synchronization-with-lock-in-python\/\",\"name\":\"Thread Synchronization with Lock in Python - TechAmass\",\"isPartOf\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/thread-synchronization-with-lock-in-python\/#primaryimage\"},\"datePublished\":\"2018-12-02T17:23:05+00:00\",\"dateModified\":\"2018-12-02T18:16:11+00:00\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/pratikkataria.com\/blog\/thread-synchronization-with-lock-in-python\/\"]}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/pratikkataria.com\/blog\/thread-synchronization-with-lock-in-python\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/thread-synchronization-with-lock-in-python\/#webpage\"},\"author\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/#\/schema\/person\/ef09a6ee5cb751524bc4c92454c59412\"},\"headline\":\"Thread Synchronization with Lock in Python\",\"datePublished\":\"2018-12-02T17:23:05+00:00\",\"dateModified\":\"2018-12-02T18:16:11+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/thread-synchronization-with-lock-in-python\/#webpage\"},\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/#\/schema\/person\/ef09a6ee5cb751524bc4c92454c59412\"},\"image\":{\"@id\":\"https:\/\/pratikkataria.com\/blog\/thread-synchronization-with-lock-in-python\/#primaryimage\"},\"keywords\":\"code,locks,parallel programming,python,threads\",\"articleSection\":\"Python,Tech\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/pratikkataria.com\/blog\/thread-synchronization-with-lock-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\/12344"}],"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=12344"}],"version-history":[{"count":3,"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/posts\/12344\/revisions"}],"predecessor-version":[{"id":12347,"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/posts\/12344\/revisions\/12347"}],"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=12344"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/categories?post=12344"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pratikkataria.com\/blog\/wp-json\/wp\/v2\/tags?post=12344"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}