{"id":1710,"date":"2020-12-17T09:22:17","date_gmt":"2020-12-17T09:22:17","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=1710"},"modified":"2023-06-03T12:16:06","modified_gmt":"2023-06-03T12:16:06","slug":"python-threading-lock","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-concurrency\/python-threading-lock\/","title":{"rendered":"How to use the Python Threading Lock to Prevent Race Conditions"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about race conditions and how to use the Python threading Lock object to prevent them.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='what-is-a-race-condition'>What is a race condition <a href=\"#what-is-a-race-condition\" class=\"anchor\" id=\"what-is-a-race-condition\" title=\"Anchor for What is a race condition\">#<\/a><\/h2>\n\n\n\n<p>A race condition occurs when two or more <a href=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-threading\/\">threads<\/a> try to access a shared variable simultaneously, leading to unpredictable outcomes.<\/p>\n\n\n\n<p>In this scenario, the first thread reads the value from the shared variable. At the same time, the second thread also reads the value from the same shared variable.<\/p>\n\n\n\n<p>Then both threads attempt to change the value of the shared variable. since the updates occur simultaneously, it creates a race to determine which thread&#8217;s modification is preserved.<\/p>\n\n\n\n<p>The final value of the shared variable depends on which thread completes its update last. Whatever thread that changes the value last will win the race. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='race-condition-example'>Race condition example <a href=\"#race-condition-example\" class=\"anchor\" id=\"race-condition-example\" title=\"Anchor for Race condition example\">#<\/a><\/h2>\n\n\n\n<p>The following example illustrates a race condition:<\/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\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> sleep\n\n\ncounter = <span class=\"hljs-number\">0<\/span>\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">increase<\/span><span class=\"hljs-params\">(by)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">global<\/span> counter\n\n    local_counter = counter\n    local_counter += by\n\n    sleep(<span class=\"hljs-number\">0.1<\/span>)\n\n    counter = local_counter\n    print(<span class=\"hljs-string\">f'counter=<span class=\"hljs-subst\">{counter}<\/span>'<\/span>)\n\n\n<span class=\"hljs-comment\"># create threads<\/span>\nt1 = Thread(target=increase, args=(<span class=\"hljs-number\">10<\/span>,))\nt2 = Thread(target=increase, args=(<span class=\"hljs-number\">20<\/span>,))\n\n<span class=\"hljs-comment\"># start the threads<\/span>\nt1.start()\nt2.start()\n\n\n<span class=\"hljs-comment\"># wait for the threads to complete<\/span>\nt1.join()\nt2.join()\n\n\nprint(<span class=\"hljs-string\">f'The final counter is <span class=\"hljs-subst\">{counter}<\/span>'<\/span>)<\/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>In this program, both threads try to modify the value of the <code>counter<\/code> variable at the same time. The value of the <code>counter<\/code> variable depends on which thread completes last.<\/p>\n\n\n\n<p>If the thread <code>t1<\/code> completes before the thread <code>t2<\/code>, you&#8217;ll see the following 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\">counter=<span class=\"hljs-number\">10<\/span>\ncounter=<span class=\"hljs-number\">20<\/span>\nThe counter <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-number\">20<\/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>Otherwise, you&#8217;ll see the following output:<\/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\">counter=<span class=\"hljs-number\">20<\/span>\ncounter=<span class=\"hljs-number\">10<\/span>\nThe final counter <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-number\">10<\/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>How it works.<\/p>\n\n\n\n<p>First, import <code>Thread<\/code> class from the <code>threading<\/code> module and the <code>sleep()<\/code> function from the <code>time<\/code> module:<\/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-keyword\">from<\/span> threading <span class=\"hljs-keyword\">import<\/span> Thread\n<span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> sleep<\/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>Second, define a global variable called <code>counter<\/code> whose value is zero:<\/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\">counter = <span class=\"hljs-number\">0<\/span><\/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>Third, define a function that increases the value of the <code>counter<\/code> variable by a number:<\/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\">increase<\/span><span class=\"hljs-params\">(by)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">global<\/span> counter\n\n    local_counter = counter\n    local_counter += by\n\n    sleep(<span class=\"hljs-number\">0.1<\/span>)\n\n    counter = local_counter\n    print(<span class=\"hljs-string\">f'counter=<span class=\"hljs-subst\">{counter}<\/span>'<\/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>Fourth, create two threads. The first thread increases the <code>counter<\/code> by 10 while the second thread increases the <code>counter<\/code> by 20:<\/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\">t1 = Thread(target=increase, args=(<span class=\"hljs-number\">10<\/span>,))\nt2 = Thread(target=increase, args=(<span class=\"hljs-number\">20<\/span>,))<\/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>Fifth, start the threads:<\/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\">t1.start()\nt2.start()<\/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>Sixth, from the main thread, wait for the threads t1 and t2 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\">t1.join()\nt2.join()<\/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>Finally, show the final value of the <code>counter<\/code> variable:<\/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\">print(<span class=\"hljs-string\">f'The final counter is <span class=\"hljs-subst\">{counter}<\/span>'<\/span>)<\/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<h2 class=\"wp-block-heading\" id='using-a-threading-lock-to-prevent-the-race-condition'>Using a threading lock to prevent the race condition <a href=\"#using-a-threading-lock-to-prevent-the-race-condition\" class=\"anchor\" id=\"using-a-threading-lock-to-prevent-the-race-condition\" title=\"Anchor for Using a threading lock to prevent the race condition\">#<\/a><\/h2>\n\n\n\n<p>To prevent race conditions, you can use a threading lock.<\/p>\n\n\n\n<p>A threading lock is a synchronization primitive that provides exclusive access to a shared resource in a multithreaded application. A thread lock is also known as a <strong>mutex<\/strong> which is short for mutual exclusion.<\/p>\n\n\n\n<p>Typically, a threading lock has two states: locked and unlocked. When a thread acquires a lock, the lock enters the locked state. The thread can have exclusive access to the shared resource.<\/p>\n\n\n\n<p>Other threads that attempt to acquire the lock while it is locked will be blocked and wait until the lock is released.<\/p>\n\n\n\n<p>In Python, you can use the <code>Lock<\/code> class from the <code><a href=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-threading\/\">threading<\/a><\/code> module to create a lock object:<\/p>\n\n\n\n<p>First, create an instance the <code>Lock<\/code> class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">lock = Lock()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><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>By default, the lock is unlocked until a thread acquires it.<\/p>\n\n\n\n<p>Second, acquire a lock by calling the <code>acquire()<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">lock.acquire()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><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, release the lock once the thread completes changing the shared variable:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">lock.release()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><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 following example shows how to use the <code>Lock<\/code> object to prevent the race condition in the previous program:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" 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, Lock\n<span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> sleep\n\n\ncounter = <span class=\"hljs-number\">0<\/span>\n\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">increase<\/span><span class=\"hljs-params\">(by, lock)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">global<\/span> counter\n\n    lock.acquire()\n\n    local_counter = counter\n    local_counter += by\n\n    sleep(<span class=\"hljs-number\">0.1<\/span>)\n\n    counter = local_counter\n    print(<span class=\"hljs-string\">f'counter=<span class=\"hljs-subst\">{counter}<\/span>'<\/span>)\n\n    lock.release()\n\n\nlock = Lock()\n\n<span class=\"hljs-comment\"># create threads<\/span>\nt1 = Thread(target=increase, args=(<span class=\"hljs-number\">10<\/span>, lock))\nt2 = Thread(target=increase, args=(<span class=\"hljs-number\">20<\/span>, lock))\n\n<span class=\"hljs-comment\"># start the threads<\/span>\nt1.start()\nt2.start()\n\n\n<span class=\"hljs-comment\"># wait for the threads to complete<\/span>\nt1.join()\nt2.join()\n\n\nprint(<span class=\"hljs-string\">f'The final counter is <span class=\"hljs-subst\">{counter}<\/span>'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><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-15\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">counter=<span class=\"hljs-number\">10<\/span>\ncounter=<span class=\"hljs-number\">30<\/span>\nThe final counter <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-number\">30<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><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<ul class=\"wp-block-list\">\n<li>First, add a second parameter to the <code>increase()<\/code> function.<\/li>\n\n\n\n<li>Second, create an instance of the <code>Lock<\/code> class.<\/li>\n\n\n\n<li>Third, acquire a lock before accessing the <code>counter<\/code> variable and release it after updating the new value.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='using-the-threading-lock-with-the-with-statement'>Using the threading lock with the with statement <a href=\"#using-the-threading-lock-with-the-with-statement\" class=\"anchor\" id=\"using-the-threading-lock-with-the-with-statement\" title=\"Anchor for Using the threading lock with the with statement\">#<\/a><\/h2>\n\n\n\n<p>It&#8217;s easier to use the lock object with the <code>with<\/code> statement to acquire and release the lock within a block of code:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import threading\r\n\r\n<span class=\"hljs-comment\"># Create a lock object<\/span>\r\nlock = threading.Lock()\r\n\r\n<span class=\"hljs-comment\"># Perform some operations within a critical section<\/span>\r\nwith lock:\r\n    <span class=\"hljs-comment\"># Lock was acquired within the with block<\/span>\r\n    <span class=\"hljs-comment\"># Perform operations on the shared resource<\/span>\r\n    <span class=\"hljs-comment\"># ...<\/span>\r\n\r\n<span class=\"hljs-comment\"># the lock is released outside the with block<\/span>\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>For example, you can use the with statement without the need of calling <code>acquire()<\/code> and <code>release()<\/code> methods in the above example as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">from threading import Thread, Lock\r\nfrom time import sleep\r\n\r\n\r\ncounter = <span class=\"hljs-number\">0<\/span>\r\n\r\ndef increase(by, lock):\r\n    <span class=\"hljs-keyword\">global<\/span> counter\r\n\r\n    with lock:\r\n        local_counter = counter\r\n        local_counter += by\r\n\r\n        sleep(<span class=\"hljs-number\">0.1<\/span>)\r\n\r\n        counter = local_counter\r\n        <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">'counter={counter}'<\/span>)\r\n\r\n\r\nlock = Lock()\r\n\r\n<span class=\"hljs-comment\"># create threads<\/span>\r\nt1 = Thread(target=increase, args=(<span class=\"hljs-number\">10<\/span>, lock))\r\nt2 = Thread(target=increase, args=(<span class=\"hljs-number\">20<\/span>, lock))\r\n\r\n<span class=\"hljs-comment\"># start the threads<\/span>\r\nt1.start()\r\nt2.start()\r\n\r\n\r\n<span class=\"hljs-comment\"># wait for the threads to complete<\/span>\r\nt1.join()\r\nt2.join()\r\n\r\n\r\n<span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">'The final counter is {counter}'<\/span>)\r\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='defining-thread-safe-counter-class-that-uses-threading-lock-object'>Defining thread-safe Counter class that uses threading Lock object <a href=\"#defining-thread-safe-counter-class-that-uses-threading-lock-object\" class=\"anchor\" id=\"defining-thread-safe-counter-class-that-uses-threading-lock-object\" title=\"Anchor for Defining thread-safe Counter class that uses threading Lock object\">#<\/a><\/h2>\n\n\n\n<p>The following illustrates how to define a <code>Counter<\/code> class that is thread-safe using the <code>Lock<\/code> object:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" 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, Lock\r\n<span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> sleep\r\n\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Counter<\/span>:<\/span>\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\r\n        self.value = <span class=\"hljs-number\">0<\/span>\r\n        self.lock = Lock()\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">increase<\/span><span class=\"hljs-params\">(self, by)<\/span>:<\/span>\r\n        <span class=\"hljs-keyword\">with<\/span> self.lock:\r\n            current_value = self.value\r\n            current_value += by\r\n\r\n            sleep(<span class=\"hljs-number\">0.1<\/span>)\r\n\r\n            self.value = current_value\r\n            print(<span class=\"hljs-string\">f'counter=<span class=\"hljs-subst\">{self.value}<\/span>'<\/span>)\r\n\r\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\r\n    counter = Counter()\r\n    <span class=\"hljs-comment\"># create threads<\/span>\r\n    t1 = Thread(target=counter.increase, args=(<span class=\"hljs-number\">10<\/span>, ))\r\n    t2 = Thread(target=counter.increase, args=(<span class=\"hljs-number\">20<\/span>, ))\r\n\r\n    <span class=\"hljs-comment\"># start the threads<\/span>\r\n    t1.start()\r\n    t2.start()\r\n\r\n\r\n    <span class=\"hljs-comment\"># wait for the threads to complete<\/span>\r\n    t1.join()\r\n    t2.join()\r\n\r\n\r\n    print(<span class=\"hljs-string\">f'The final counter is <span class=\"hljs-subst\">{counter.value}<\/span>'<\/span>)\r\n\r\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">'__main__'<\/span>:\r\n    main()\r\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><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>A race condition occurs when two threads access a shared variable at the same time.<\/li>\n\n\n\n<li>Use a threading lock object to prevent the race condition<\/li>\n\n\n\n<li>Call the <code>acquire()<\/code> method of a lock object to acquire a lock.<\/li>\n\n\n\n<li>Call the <code>release()<\/code> method of a lock object to release the previously acquired lock.<\/li>\n\n\n\n<li>Use a threading lock object with the <code>with<\/code> statement to make it easier to acquire and release the lock.<\/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=\"1710\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-threading-lock\/\"\n\t\t\t\tdata-post-title=\"How to use the Python Threading Lock to Prevent Race Conditions\"\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=\"1710\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-threading-lock\/\"\n\t\t\t\tdata-post-title=\"How to use the Python Threading Lock to Prevent Race Conditions\"\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>Summary: in this tutorial, you&#8217;ll learn about race conditions and how to use the Python threading Lock object to prevent them. What is a race condition # A race condition occurs when two or more threads try to access a shared variable simultaneously, leading to unpredictable outcomes. In this scenario, the first thread reads the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":4104,"menu_order":7,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1710","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1710","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=1710"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1710\/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=1710"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}