英文:
Force a "lock" with Postgres and GO
问题
我是新手Postgres,所以这可能很明显(或者非常困难,我不确定)。
我想要强制一个表或行在一段时间内被“锁定”,这将导致第二个操作“等待”。
我正在使用golang和“github.com/lib/pq”与数据库进行交互。
我需要这样做的原因是因为我正在开发一个监控PostgreSQL的项目。谢谢任何帮助。
英文:
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.
答案1
得分: 7
你也可以使用select ... for update来锁定一行或多行数据,以确保在事务期间保持锁定状态。
基本上,它的用法如下:
begin;
select * from foo where quatloos = 100 for update;
update foo set feens = feens + 1 where quatloos = 100;
commit;
这将对foo表中quatloos等于100的行执行独占的行级锁定。任何试图访问这些行的其他事务将被阻塞,直到执行commit或rollback以释放select for update的锁定。
理想情况下,这些锁定应该尽可能短暂。
参考文档:https://www.postgresql.org/docs/current/static/explicit-locking.html
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论