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

Understanding basic locking

In this section, you will learn about basic locking mechanisms. The goal is to understand how locking works in general and how to get simple applications right.

To show you how things work, we will create a simple table. For demonstrative purposes, I will add one row to the table using a simple INSERT command:

test=# CREATE TABLE  t_test (id int);  
CREATE TABLE 
test=# INSERT INTO t_test VALUES (0); 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 any problems.

The question now is what happens if reads and writes occur at the same time? Here is an example. Let's assume that the table contains one row and its id = 0:

 

Two transactions are opened. The first one will change a row. However, this is not a problem as the second transaction can proceed. It will return the old row as it was before UPDATE. This behavior is called Multi-Version Concurrency Control (MVCC).

A transaction will only see data if it has been committed by the write transaction before the initiation of the read transaction. One transaction cannot inspect the changes that have been made by another 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 2018) unable to handle concurrent reads and writes. In PostgreSQL, this is absolutely not a problem—reads and writes can coexist.

Write transactions won't block read transactions.

After the transaction has been committed, the table will contain 1.

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 preceding code, no hit will be lost because PostgreSQL guarantees that one UPDATE statement is performed after the other.

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

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

主站蜘蛛池模板: 河南省| 托里县| 石棉县| 弥渡县| 平塘县| 三台县| 庄河市| 新疆| 保靖县| 长葛市| 和顺县| 甘孜县| 金山区| 洛扎县| 阿拉善盟| 宁河县| 大庆市| 睢宁县| 资溪县| 邳州市| 长丰县| 章丘市| 通河县| 湖州市| 和硕县| 平安县| 廊坊市| 萨嘎县| 昭平县| 兰坪| 东阿县| 奎屯市| 错那县| 康马县| 柳林县| 石景山区| 廊坊市| 长宁区| 兴宁市| 东港市| 雷州市|