我有一个多线程的外部应用程序,这个应用程序正在使用我的自定义 dll 从该线程执行一些操作。
在此 dll 中,我有 2 个函数,用于读取和写入一些数据到 TList
。
我需要这些线程可以自由读取该列表,但一次只有一个可以写入,其余的必须等待写入的时间。
我的问题:
- BDS 2006 中是否有一个具有 TMREWSync 功能的 TList
组件或
- 也许您知道我可以在我的应用程序中使用的任何免费第三方组件或
- 也许您有一些自定义的 TList
代码可以执行上述操作。
编辑:
我需要类似 TThreadList.LockList
的东西,但仅用于写入该列表。
感谢您的帮助。
最佳答案
以与 TThreadList
相同的方式将 TMultiReadExclusiveWriteSynchronizer
和 TList
组合在一起非常简单。如果您已经知道这些类是如何工作的,那么您将能够按照下面的代码进行操作。
type
TReadOnlyList = class
private
FList: TList;
function GetCount: Integer;
function GetItem(Index: Integer): Pointer;
public
constructor Create(List: TList);
property Count: Integer read GetCount;
property Items[Index: Integer]: Pointer read GetItem;
end;
TMREWList = class
private
FList: TList;
FReadOnlyList: TReadOnlyList;
FLock: TMultiReadExclusiveWriteSynchronizer;
public
constructor Create;
destructor Destroy; override;
function LockListWrite: TList;
procedure UnlockListWrite;
function LockListRead: TReadOnlyList;
procedure UnlockListRead;
end;
{ TReadOnlyList }
constructor TReadOnlyList.Create(List: TList);
begin
inherited Create;
FList := List;
end;
function TReadOnlyList.GetCount: Integer;
begin
Result := FList.Count;
end;
function TReadOnlyList.GetItem(Index: Integer): Pointer;
begin
Result := FList[Index];
end;
{ TMREWList }
constructor TMREWList.Create;
begin
inherited;
FList := TList.Create;
FReadOnlyList := TReadOnlyList.Create(FList);
FLock := TMultiReadExclusiveWriteSynchronizer.Create;
end;
destructor TMREWList.Destroy;
begin
FLock.Free;
FReadOnlyList.Free;
FList.Free;
inherited;
end;
function TMREWList.LockListWrite: TList;
begin
FLock.BeginWrite;
Result := FList;
end;
procedure TMREWList.UnlockListWrite;
begin
FLock.EndWrite;
end;
function TMREWList.LockListRead: TReadOnlyList;
begin
FLock.BeginRead;
Result := FReadOnlyList;
end;
procedure TMREWList.UnlockListRead;
begin
FLock.EndRead;
end;
这是最基本的实现。如果您愿意,可以通过 TThreadList
的方式添加更多花哨的功能。
关于multithreading - Delphi2006 - 是否有带有 TMultiReadExclusiveWriteSynchronizer 的 TList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15199584/