简体   繁体   中英

Force a “lock” with Postgres and GO

I am new to Postgres so this may be obvious (or very difficult, I am not sure).

I would like to force a table or row to be "locked" for at least a few seconds at a time. Which will cause a second operation to "wait".

I am using golang with "github.com/lib/pq" to interact with the database.

The reason I need this is because I am working on a project that monitors postgresql. Thanks for any help.

You can also use select ... for update to lock a row or rows for the length of the transaction.

Basically, it's like:

begin;
select * from foo where quatloos = 100 for update;
update foo set feens = feens + 1 where quatloos = 100;
commit;

This will execute an exclusive row-level lock on foo table rows where quatloos = 100. Any other transaction attempting to access those rows will be blocked until commit or rollback has been issued once the select for update has run.

Ideally, these locks should live as short as possible.

See: https://www.postgresql.org/docs/current/static/explicit-locking.html

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