When will two mutexes be needed?

Hello, everyone. I"m learning about mutexes.
what I don"t understand is that there are two situations in which deadlocks occur:

1, in general, if the same thread calls lock, twice in the second call, because the lock is already occupied, the thread will hang and wait for other threads to release the lock, but the lock is occupied by itself, and the thread is suspended without a chance to release the lock, so it will always be in a suspended waiting state, which is called deadlock (Deadlock).

2, another: if thread An acquires lock 1 and thread B acquires lock 2, thread A calls lock to try to acquire lock 2, the result is that thread B needs to suspend waiting thread B to release lock 2, and thread B also calls lock to try to obtain lock 1, the result is that thread A needs to suspend waiting thread A to release lock 1, so threads An and B are in a suspended state forever.

case 1 I understand that if I lock it and then try to lock it, I will deadlock
the second way I don"t understand, why are there two locks? What I can understand is that two locks are set, and the properties of the two locks are different. only at this time, two locks are needed, and it is impossible to have two locks with the same properties. Moreover, this method of obtaining lock An and requesting lock B is also a fault usage and is meaningless.

is my thinking correct?
/ br > I read the tutorial online and saw that there are two situations in which deadlocks occur when I feel that I am not clear.
when I read the tutorial on the Internet, I saw that there are two situations in which deadlocks occur.
1. After the thread calls lock, lock continues without unlock.
2, thread An acquires lock 1, thread B acquires lock 2; then An invokes lock 2, and B invokes lock 1, causing each other to wait for a deadlock.
when the problem 1:intpthread_mutex_init initializes, no data is specified, and the critical area data in this process will be locked, so a lock can lock the process data. Does a process need only one lock?
question 2: there are many properties of locks. If a process has multiple locks, it must be multiple types of locks.

Dec.11,2021

most locks are reentrant, so it is possible for the same thread to acquire the same lock multiple times without hanging.

the second problem is also easy to understand. Locks are used to protect resources, and when there are multiple resources in the program, multiple locks may be needed to protect them.


Lock locks one piece of data, not the entire database, otherwise the concurrency is much worse
for example, when An is transferred to B, An is transferred to B, and then B is locked. If there is another request from B to An at this time (then the service needs to lock B before locking A), deadlock may occur. The solution is to lock according to the user's id order

Menu