官术网_书友最值得收藏!

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.

Multiple users can read the same data at the same time without blocking each other.

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.

A transaction can see only those changes that have already been committed.

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.

Writing transactions won't block reading transactions.

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.

PostgreSQL will only lock rows affected by the UPDATE. So if you have 1,000 rows, you can theoretically run 1,000 concurrent changes on the same table.

It is also noteworthy that you can always run concurrent reads. Our two writes will not block reads.

主站蜘蛛池模板: 囊谦县| 萍乡市| 余江县| 玉门市| 洪江市| 那坡县| 法库县| 仁寿县| 瑞金市| 吉木萨尔县| 红安县| 甘孜| 南宁市| 汾阳市| 云南省| 溧水县| 弥渡县| 新干县| 巫山县| 莫力| 绍兴县| 武邑县| 句容市| 牟定县| 芜湖县| 铜梁县| 方正县| 长岛县| 湛江市| 沾益县| 徐汇区| 闸北区| 伊川县| 安吉县| 金溪县| 桂平市| 锦屏县| 原平市| 三门县| 定南县| 武乡县|