简体   繁体   中英

How to run multiple transactions concurrently in PostgreSQL

I want to do some basic experiment on PostgreSQL, for example to generate deadlocks, to create non-repeatable reads, etc. But I could not figure out how to run multiple transactions at once to see such behavior. Can anyone give me some Idea?

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; 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 is probably the best solution in yours case. It allows you to test different complex database resource contentions, deadlocks, multi-client, multi-threaded access.

To get dealocks you can simply right some script like this ('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;

and pass it to pgbench with -f parameter.

For more detailed pgbench usage I would recommend to read the official manual for postgreSQL pgBench

and get acquented with my pgbench question resolved recently here .

Craig Ringer提供了一种手动打开多个事务的方法,如果发现不是很方便,可以使用pgbench一次运行多个事务。

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