我想在 PostgreSQL 上做一些基本的实验,例如生成死锁、创建不可重复读取等。但我不知道如何一次运行多个事务来查看这种行为。谁能给我一些想法?
3 回答
Open more than one psql
session, one terminal per session.
If you're on Windows you can do that by launching psql
via the Start menu multiple times. On other platforms open a couple of new terminals or terminal tabs and start psql
in each.
I routinely do this when I'm examining locking and concurrency issues, used in answers like:
... probably more. A useful trick when you want to set up a race condition is to open a third psql
session and BEGIN; LOCK TABLE the_table_to_race_on;
. Then run statements in your other sessions; they'll block on the lock. ROLLBACK
the transaction holding the table lock and the other sessions will race. It's not perfect, since it doesn't simulate offset-start-time concurrency, but it's still very helpful.
Other alternatives are outlined in this later answer on a similar topic.
pgbench 可能是您的最佳解决方案。它允许您测试不同的复杂数据库资源争用、死锁、多客户端、多线程访问。
要获得解除锁定,您可以简单地纠正一些像这样的脚本('bench_script.sql):
DECLARE cnt integer DEFAULT 0;
BEGIN;
LOCK TABLE schm.tbl IN SHARE MODE;
select count(*) from schm.tabl into cnt;
insert into schm.tbl values (1 + 9999*random(), 'test descr' );
END;
并使用 -f 参数将其传递给 pgbench。
有关更详细的 pgbench 用法,我建议阅读postgreSQL pgBench的官方手册
并熟悉我最近在这里解决的 pgbench 问题。
Craig Ringer 提供了一种手动开启多个事务的方式,如果你觉得不太方便,可以使用pgbench一次运行多个事务。