How to use semaphore to lock table?

一世执手 提交于 2019-12-12 02:33:02

问题


I would like to lock an MDB table from reads while a transaction executes. I would use dbDenyRead but apparently this is unreliable and doesn't always the lock the table:

http://www.office-archive.com/32-ms-access/c2bd1a2553e79c60.htm

How can I use a semaphore solution to achieve a virtual lock on a table?

If I store the semaphore in another table with a row holding the table name and a process/workstation ID which will be cleared at the end of the transaction, how can I prevent the following sequence?

  1. Process A queries semaphore table and finds it blank.
  2. Process B queries semaphore table and finds it blank.
  3. Process A updates semaphore table with Process A ID.
  4. Process B updates semaphore table with Process B ID.
  5. Both Process A and B perform transaction (not what I want).

Please no answers that include the use of the IF SQL statement because my version of JET-SQL can't use that.


回答1:


I'm not sure if this will address all of your issues. But create a table with a Primary Key that isn't auto-generated. If possible, also declare the same column with some kind of check/rule that enforces that the column may only contain one possible value.

You now have a table that can contain 0 or 1 rows. To obtain the "semaphore", insert a row into the table, with the single fixed PK value. If this insert succeeds, you own the semaphore. If the insert fails due to a primary key violation, then you didn't obtain the semaphore. The key is to not perform a preliminary check first - just attempt the insert.

If your tech is so broken that it can't guarantee that the PK constraint will be maintained, then you seriously need to consider changing technology.

If you fail to insert the row, then you can start regularly polling this table - at whatever intervals seem appropriate.


The other alternative is to have the table have an autonumber PK column - when you want to obtain the semaphore, insert a row into the table. Then, query the table to locate the row with the lowest PK column value. If that row is your row, then you now own the semaphore. You still have to poll, but you effectively have a "reservation" recorded in this table.

As with the previous case, once you have completed your semaphore protected work, you delete your row from the table. This second approach should be "fairer" (in that each process gains access in strict order of requests), but may look be messier in practice. It does rely on all processes staying "live".



来源:https://stackoverflow.com/questions/12662152/how-to-use-semaphore-to-lock-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!