Multi-User Locking Methods in Visual Basic

本文主要探讨Visual Basic中多用户数据库访问的锁定方法,重点是页面锁定。介绍了悲观锁定和乐观锁定两种类型,指出使用时需注意的问题,如锁定冲突、索引页锁定等,还提及页面级锁定的两种主要运行时错误及处理示例。

Multi-User Locking Methods in Visual Basic

By: Kevin Laughton


Id like to thank Don Willits (Microsoft) for his assistance.

Multi-user database access has been a trial and error approach for most of us. While there are really three choices of locking scenarios, only one is a real concern. The first method is to lock the entire Database by opening it exclusively. Obviously, this is not an option in a multi-user environment due to the brutal impact it would have on all but the first user. For pretty much the same reason, option number 2, Table locking, is also out. So the focus of this article is on choice number 3, Page locking. While you may already know about page locking, I urge you to read on since I'll mention a couple of things in here that I don't think you'll find anywhere else.

99% of the time a multi-user system wants to lock the smallest amount of data possible so as to not hinder the performance of other users. Since VB does not support record locking, the smallest amount of data rows that can be locked is a Page or roughly 2K of data. Actually locking the page is not the focus of this article; the reason being that this is done AUTOMATICALLY for you by the Access database engine (JET). However, we must write code that will effectively handle situations where we try to update a record in a locked page.

At this point I should mention the different types of page locking. The default page locking type is Pessimistic Locking. Lets use the Edit and Update methods for manipulating the database. In Pessimistic locking, the page is locked when you make the call to the Edit method and unlocks the page when you make the Update method call. The second locking type is Optimistic locking. Using this type of locking, the page is locked only when you make the Update method call. Well have to do some extra work in this case, but it is an option.

There are a few things to bear in mind that are not particularly clear from the manuals. First, since the entire page is locked, and a given page may contain more then one record, users need not be on the exact same record to cause a locking conflict. Second, these locking methods apply to the index pages as well. What this means is that when the Seek method is used or indexes are being rebuilt, the index pages are locked on a 2K page basis. This can also cause locking errors, which the programmer should handle appropriately. Third, the AddNew method also locks the page the same way an Edit method call does. This prevents two users from adding the same data to a table and causing other types of errors.

Speaking of errors, there are two main run-time errors to trap for with page level locking. The first is error 3260 "Couldnt Update; currently locked by user x on machine y." This error means that another user has already locked the page containing your data.

The second is error 3197 "Data has changed; operation stopped." In this case the data you retrieved and are trying to update has already been changed by another user. In other words, the set of data you are currently dealing with is out of date. This error is just warning you that you are about to overwrite someone elses work. Its as if we both opened a MS Word document and I tried to save my changes just after you did. If I didnt get an error I would overwrite all of your changes with mine. This error occurs only once per operation, so if you try the same operation again, you wont get the error generated again.

One interesting thing about Error 3197 and SnapShots is that you can generate this error just by moving through a SnapShot the contains Memo fields. Since Memo fields can be really large, SnapShots only contain references to them as opposed to placing the whole memo contents into the SnapShot. If I go to record 10 and you update record 5, the next time I visit record 5 by moving to it, I will generate a 3197 error since the data has been changed.

Here is an example of multi-user database page locking and the error handling needed to make it work. Note that the database routines are pulled from my CyberStyle column and can be found in the module DB.BAS. Please refer to the CyberStyle section for an explanation of how they work. Also note that I have not included any code that makes use of the data control supplied with VB3. It has been my experience that the data control is of little value in the real world and that true power and control only comes with using the data access objects in the VB3 professional edition.

Const MB_RETRYCANCEL = 5
Const MB_YESNO = 4
Const IDCANCEL = 2
Const IDRETRY = 4
Const IDNO = 7
Const DB_DENYWRITE = &H1
Const DB_DENYREAD = &H2
Const ERR_RESERVED = 3000
Const ERR_CANT_OPEN_DB = 3051
Const ERR_CANT_LOCK_TABLE = 3262
Const ERR_DATA_CHANGED = 3197
Const ERR_RECORD_LOCKED = 3260
Const RERR_ExclusiveDBConflict = "-8194"

Sub Command1_Click ()

Dim db As database
Dim ads() As Dynaset
Dim ds As Dynaset 'Used only to keep code simple
Dim ret As Integer
Dim bUnLocked As Integer

ret% = DB_Connect("BIBLIO.MDB")
ret% = DB_Query2Dyna("Authors", ads())

'This next line is not needed but makes the code easier to read without the ads(0) stuff.
Set ds = ads(0).Clone()

Do Until ds.EOF = True
'Attempt to access records, checking for possible page locking conflicts
bUnLocked = False
'Disable any previous error handler and instead, just resume next
On Error Resume Next
While Not bUnLocked
Err = 0
ds.Edit
Select Case Err
Case 0
'No error happened...OK
bUnLocked = True

Case ERR_DATA_CHANGED
ret% = MsgBox("Record has been updated. Overwrite?", MB_RETRYCANCEL)

Case ERR_RECORD_LOCKED
ret% = MsgBox("Record in use by another user. Try Again?", MB_RETRYCANCEL)

Case Else
MsgBox "Unexpected error" & Str$(Err) & " editing record."
Exit Sub
End Select

Select Case ret%
Case IDCANCEL
'Cancel means quit the Functon
Exit Sub
Case IDRETRY
'Retry means try again in the loop. Note that the retry for the ERR_DATA_CHANGED
' will always work the second time through since the Edit method will
' not generate this error again for this series of events.
bUnLocked = False
End Select
Wend
'disable error trapping OR place On Error statements
'pointing to a new error handler here
On Error GoTo 0

ds("Author") = ds("Author")

' With Optimistic locking you would check locking on Update vs. Edit
ds.Update
ds.MoveNext
Loop

ret% = DB_CloseDyna(ds)
ret% = DB_CloseDatabase()
End Sub

For Optimistic locking, you would want to check for locking errors on the Update method, rather then the Edit methods.

【电力系统】单机无穷大电力系统短路故障暂态稳定Simulink仿真(带说明文档)内容概要:本文档围绕“单机无穷大电力系统短路故障暂态稳定Simulink仿真”展开,提供了完整的仿真模型与说明文档,重点研究电力系统在发生短路故障后的暂态稳定性问题。通过Simulink搭建单机无穷大系统模型,模拟不同类型的短路故障(如三相短路),分析系统在故障期间及切除后的动态响应,包括发电机转子角度、转速、电压和功率等关键参数的变化,进而评估系统的暂态稳定能力。该仿真有助于理解电力系统稳定性机理,掌握暂态过程分析方法。; 适合人群:电气工程及相关专业的本科生、研究生,以及从事电力系统分析、运行与控制工作的科研人员和工程师。; 使用场景及目标:①学习电力系统暂态稳定的基本概念与分析方法;②掌握利用Simulink进行电力系统建模与仿真的技能;③研究短路故障对系统稳定性的影响及提高稳定性的措施(如故障清除时间优化);④辅助课程设计、毕业设计或科研项目中的系统仿真验证。; 阅读建议:建议结合电力系统稳定性理论知识进行学习,先理解仿真模型各模块的功能与参数设置,再运行仿真并仔细分析输出结果,尝试改变故障类型或系统参数以观察其对稳定性的影响,从而深化对暂态稳定问题的理解。
### 三级标题:Next-Key Locking机制概述 Next-Key Locking 是 MySQL InnoDB 存储引擎中的一种锁机制,它结合了行锁(Record Lock)和间隙锁(Gap Lock)的功能,用于保证事务的隔离性,特别是在可重复读(Repeatable Read)隔离级别下。该机制通过锁定索引记录及其周围的间隙,防止其他事务插入或修改数据,从而避免了幻读问题[^1]。 ### 三级标题:Next-Key Locking 的工作原理 Next-Key Locking 的核心在于同时锁定记录和记录之间的间隙,形成一个左开右闭的区间。例如,对于表中已有记录 `[10, 20, 30]`,当执行 `SELECT * FROM t WHERE id > 15 FOR UPDATE` 时,InnoDB 会锁定以下区间: - `(10, 20]`:对应记录 20 的临键锁 - `(20, 30]`:对应记录 30 的临键锁 - `(30, +&infin;)`:对应 Supremum 伪记录的间隙锁 这种锁机制确保了在事务执行期间,其他事务无法在这些区间内插入新的记录,从而避免了幻读现象[^3]。 ### 三级标题:Next-Key Locking 的应用场景 Next-Key Locking 主要应用于以下场景: - **可重复读(Repeatable Read)隔离级别**:这是 InnoDB 的默认隔离级别,在此级别下,Next-Key Locking 用于防止幻读问题。 - **范围查询(Range Query)**:当执行 `SELECT ... FOR UPDATE` 或 `SELECT ... LOCK IN SHARE MODE` 时,InnoDB 会对查询范围内的记录及其间隙加锁,防止其他事务插入新记录。 - **唯一性约束检查**:在某些情况下,Next-Key Locking 也用于防止违反唯一性约束的数据插入。 ### 三级标题:Next-Key Locking 的并发性能影响 尽管 Next-Key Locking 能够有效防止幻读问题,但它也会带来一定的并发性能开销。由于锁定了记录及其周围的间隙,多个事务在操作相邻数据时可能会发生锁冲突,导致事务等待甚至死锁。因此,在实际业务场景中,需要权衡一致性与并发性能之间的关系,合理使用该机制[^1]。 ### 三级标题:C++ 代码实现示例 以下是一个简化的锁区间管理器实现,用于模拟 Next-Key Locking 的部分逻辑: ```cpp #include <iostream> #include <map> #include <mutex> #include <vector> struct LockRange { int64_t left; // 左边界(不包含) int64_t right; // 右边界(包含) std::mutex mtx; LockRange(int64_t l, int64_t r) : left(l), right(r) {} }; class LockManager { std::map<int64_t, LockRange*> lock_ranges; // 按右边界排序的区间集合 std::mutex global_mtx; public: bool acquire_lock(int64_t key) { std::lock_guard<std::mutex> lock(global_mtx); // 查找第一个右边界 >= key 的区间 auto it = lock_ranges.lower_bound(key); if (it != lock_ranges.end() && key > it->second->left) { // 冲突:区间被其他事务锁定 return false; } // 创建新锁区间(示例逻辑,实际上需要合并相邻区间) LockRange* new_range = new LockRange(key - 1, key); lock_ranges.emplace(key, new_range); return true; } void release_lock(int64_t key) { std::lock_guard<std::mutex> lock(global_mtx); auto it = lock_ranges.find(key); if (it != lock_ranges.end()) { delete it->second; lock_ranges.erase(it); } } }; int main() { LockManager manager; std::vector<int64_t> keys = {15, 25, 35}; for (auto key : keys) { if (manager.acquire_lock(key)) { std::cout << "Lock acquired for key: " << key << std::endl; } else { std::cout << "Failed to acquire lock for key: " << key << std::endl; } } for (auto key : keys) { manager.release_lock(key); std::cout << "Lock released for key: " << key << std::endl; } return 0; } ``` 上述代码展示了如何通过 C++ 实现一个简单的锁区间管理器,用于模拟 Next-Key Locking 的部分行为。该实现包括加锁和释放锁的基本逻辑,但并未处理区间合并等复杂情况。 ### 三级标题:总结 Next-Key Locking 是一种结合行锁和间隙锁的机制,能够有效防止幻读问题,适用于可重复读隔离级别下的范围查询和唯一性约束检查。然而,它也会带来一定的并发性能开销,因此在实际应用中需要根据具体业务需求进行权衡。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值