Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

threading lock example

from threading import Thread, Lock
from time import sleep


class Counter:
    def __init__(self):
        self.value = 0
        self.lock = Lock()

    def increase(self, by):
        self.lock.acquire()

        current_value = self.value
        current_value += by

        sleep(0.1)

        self.value = current_value
        print(f'counter={self.value}')

        self.lock.release()


counter = Counter()

# create threads
t1 = Thread(target=counter.increase, args=(10, ))
t2 = Thread(target=counter.increase, args=(20, ))

# start the threads
t1.start()
t2.start()


# wait for the threads to complete
t1.join()
t2.join()


print(f'The final counter is {counter.value}')
Code language: Python (python)
Comment

PREVIOUS NEXT
Code Example
Python :: python list example 
Python :: threshold image segmentation code python 
Python :: generating cross tables after clustering 
Python :: auto clicker 
Python :: what is PaasLib 
Python :: rich import in python 
Python :: debug forbidden by robots.txt scrappy 
Python :: HIDING AND ENCRYPTING PASSWORDS IN PYTHON USING MASKPASS MODULE 
Python :: sanic ip whitelist 
Python :: critical errors python 
Python :: Understand the most appropriate graph to use for your dataset 
Python :: subprocess readline blocking problem 
Python :: dropping original values after merging scaled values 
Python :: pytorch plot batch 
Python :: Dataframe with defined shape filled with 0 
Python :: extract arabic text from image python 
Python :: filter parent based on related child name values 
Python :: python chatbot speech recognition 
Python :: python cd to file 
Python :: how to get a rectangular grid out of two given one-dimensional arrays 
Python :: qlabel click python 
Python :: python lxml get parent 
Python :: can you use the astro a50 with a phone 
Python :: pop function second argument in python 
Python :: how to get python to write to 100 
Python :: add up all the numbers in each row and output that number output the grand total of all rows 
Python :: ciclo while python 
Python :: integer to boolean numpy 
Python :: write in multiple files python 
Python :: get_absolute_url method on the model 
ADD CONTENT
Topic
Content
Source link
Name
7+2 =