- Mastering PostgreSQL 9.6
- Hans Jurgen Schonig
- 374字
- 2021-07-09 19:57:12
Understanding basic locking
In this section, you will learn about basic locking mechanisms. The goal is to make you understand how locking works in general and how to get simple applications right.
To show how things work, a simple table can be created. For demonstration purposes, I will add one row to the table:
test=# CREATE TABLE t_test (id int);
CREATE TABLE
test=# INSERT INTO t_test VALUES (1);
INSERT 0 1
The first important thing is that tables can be read concurrently. Many users reading the same data at the same time won't block each other. This allows PostgreSQL to handle thousands of users without problems.
The question now is: what happens if reads and writes occur at the same time? Here is an example:

Two transactions are opened. The first one will change a row. However, this is no problem as the second transaction can proceed. It will return the old row as it was before the UPDATE. This behavior is called Multi-Version Concurrency Control (MVCC).
Note that a transaction will see data only if it has been committed by the writing transaction. One transaction cannot inspect the changes made by an active connection.
There is also a second important aspect: many commercial or open source databases are still (as of 2017) unable to handle concurrent reads and writes. In PostgreSQL, this is absolutely not a problem. Reads and writes can coexist.
After the data has been committed, the table will contain 2.
What will happen if two people change data at the same time? Here is an example:

Suppose you want to count the number of hits on a website. If you run the code as outlined just now, no hit can be lost because PostgreSQL guarantees that one UPDATE is performed after the other.
It is also noteworthy that you can always run concurrent reads. Our two writes will not block reads.
- 計(jì)算機(jī)應(yīng)用
- 智能傳感器技術(shù)與應(yīng)用
- WOW!Illustrator CS6完全自學(xué)寶典
- Visual C# 2008開發(fā)技術(shù)詳解
- CorelDRAW X4中文版平面設(shè)計(jì)50例
- 數(shù)據(jù)挖掘方法及天體光譜挖掘技術(shù)
- WordPress Theme Development Beginner's Guide(Third Edition)
- MATLAB/Simulink權(quán)威指南:開發(fā)環(huán)境、程序設(shè)計(jì)、系統(tǒng)仿真與案例實(shí)戰(zhàn)
- OpenStack Cloud Computing Cookbook
- Extending Ansible
- 在實(shí)戰(zhàn)中成長:C++開發(fā)之路
- 基于Proteus的單片機(jī)應(yīng)用技術(shù)
- Windows 7來了
- 開放自動(dòng)化系統(tǒng)應(yīng)用與實(shí)戰(zhàn):基于標(biāo)準(zhǔn)建模語言IEC 61499
- 新世紀(jì)Photoshop CS6中文版應(yīng)用教程