Senior
How to implement a simple lock mechanism in memory to protect against concurrent access without using external dependencies?
sobes.tech AI
Answer from AI
In Python, to implement a simple in-memory locking mechanism without external dependencies, you can use the built-in threading module and the Lock class. It provides mutual exclusion (mutex), allowing you to protect a critical section from concurrent access by different threads.
Example:
import threading
lock = threading.Lock()
shared_resource = 0
def critical_section():
global shared_resource
with lock: # lock
# critical section
temp = shared_resource
temp += 1
shared_resource = temp
# Starting multiple threads
threads = [threading.Thread(target=critical_section) for _ in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
print(shared_resource) # Expected 10
If you need locking between processes, you can use multiprocessing.Lock. For lower-level or more specific cases, you can implement a spinlock based on atomic operations, but this is more complex and rarely necessary.