...

/

Mechanisms for Sharing Resources

Mechanisms for Sharing Resources

Learn about three mechanisms for sharing resources between threads in Python.

We'll cover the following...

Python’s threading module provides three mechanisms for sharing resources between threads in different situations:

  • For synchronized access to shared resources, use a lock Lock.
  • For nested access to shared resources, use the reentrant lock RLock.
  • For permitting a limited number of accesses to a resource, use a semaphore.

Lock

Locks are used to synchronize access to a shared resource. We first create a Lock object. When we need to access the resource, we call acquire(), then use the resource, and once done, we call release(), as shown below:

Press + to interact
import threading
lck = threading.Lock()
lck.acquire( )
# use the resource
print('Lock acquired')
lck.release( )
print('Lock released')

Note: A lock can be in two states—locked or unlocked. ...