简体   繁体   中英

How does a database decide which process it should give the lock to, when there's two or more processes requesting for it at the exact same time?

I know that a database will always allow the first process to query it to have the lock on that row/table. But what happens when a database receives the exact same query from multiple processes at the exact same time? Does it decide randomly on which process it will first grant the lock to?

An example would be two customers requesting to buy a burger and the database has 1 burger only. Their queries reach the server at the exact same moment. Which unlucky customer will lose their lunch?

Note: I mostly use SQL Server.

From the point of view of the database software, there is no such thing as the "same time." But let's say you have a multi-processor system with two network interfaces and two requests end up getting handled at exactly the same CPU clock cycle-- very unlikely (there are billions of cycles per second) but not completely impossible.

There will be a thread for each request. Each thread will need to acquire a database lock, which presumably is held somewhere in memory. The lock will be protected by an operating system lock which will prevent both threads from accessing the database lock at the same time.

The operating system lock, ultimately, also depends on memory access. In order to access the memory, the CPU places a lock on it and transfers a copy of it into onboard cache. The other CPU won't be able to access it until the first CPU is done. So only one CPU will be able to write to the memory to get the O/S lock to get the database lock.

If by some coincidence, both CPUs request the same segment of memory at exactly the same time and both try to acquire the memory lock, the two requests are resolved by "bus arbitration," which could work several ways. It may end up depending on which CPU is physically closer to the bus line, or it might depend on which CPU has the higher device ID.

An application that uses a database will never have to worry about minuscule details like this. It's taken care of by the database platform, by the O/S, the CPU, and ultimately the physical hardware.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM