function mobileExist(mobile : Int64) : boolean;
begin
kbmtblPublic.Lock;
result := kbmtblPublic.Locate('mobile',mobile,[]);
kbmtblPublic.Unlock;
end;
...全文
1791打赏收藏
KbmMemTable 在多线程下使用是否要先lock,用完再unlock?
KbmMemTable 在多线程下使用是否要先lock,用完再unlock? function mobileExist(mobile : Int64) : boolean; begin kbmtblPublic.Lock; result := kbmtblPublic.Locate('mobile',mobile,[]); kbmtblPublic.Unlock; end;
Yes, kbmMemTable is 100% threadsafe.
There are several ways to access the memory table from several threads:
1) Have a base kbmMemTable containing data. Then have another TkbmMemTable in each of the threads which attach to the base kbmMemTable. The threads will be having each their own cursor into the base memtable, which means they can also sort and index, and filter etc. totally independent of eachother.
2) Let each thread do mt.Lock right before using it, and mt.Unlock right after. This makes sure that the operation is not interrupted by another thread. Eg. mt.Append; mt.Fields[...]:=...; mt.Post; is 3 steps. If another thread for example do a mt.Cancel in the middle of these 3 steps, either the mt.Fields... or the mt.Post will fail with an exception since the dataset is suddenly not in edit mode anymore.
kbmMemTable will not crash because of this (because internally it _is_ threadsafe) but applications will not behave as expected. Thus put a mt.Lock before the Append statement and a mt.Unlock after the Post statement.