This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import threading | |
| num = 0 | |
| lock = Threading.Lock() | |
| lock.acquire() | |
| num += 1 | |
| lock.acquire() # This will block. | |
| num += 2 | |
| lock.release() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import random, time | |
| from threading import BoundedSemaphore, Thread | |
| max_items = 5 | |
| container = BoundedSemaphore(max_items) # consider this as a container with a capacity of 5 items. | |
| # Defaults to 1 if nothing is passed. | |
| def producer(nloops): | |
| for i in range(nloops): | |
| time.sleep(random.randrange(2, 5)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from threading import Lock, Thread | |
| lock = Lock() | |
| g = 0 | |
| def add_one(): | |
| global g # Just used for demonstration. It’s bad to use the ‘global’ statement in general. | |
| lock.acquire() | |
| g += 1 | |
| lock.release() |
NewerOlder