A lock is a synchronization primitive which limits access to a shared resource among multiple threads. We don’t need locks when only one thread is running or there is no shared resource because lock is always acquired on a shared resource. Let’s look at what locks can be acquired.
Read Lock
Multiple threads can acquire read lock at the same time. However, while holding the lock, they can only read the data. Also, no other thread can update the data while the read lock is acquired.
In other words, during the period of holding the read lock on data, it’s guaranteed that the data haven’t been changed by any thread.
Write Lock
Write lock can be acquired by only one thread at a time. During the lock holding period, the thread can read or write data. If a write lock has been acquired, no other threads can read the data or acquire a read lock on the data.
In short, during the period of holding the write lock on data, it’s guaranteed that the data haven’t been read or changed by any thread.
Write lock is more strict than the read lock and ensures better synchronization. In a multithreaded application, we usually go for the read lock if we’re only reading data and taking decisions based on the read data. That’s why we need to ensure that whatever we have read for taking the decisions must be true until the processing has been done and a response has been sent to the client.
Top comments (0)