一般语言都会提供一些逻辑容器的实现,各个语言的实现方式不同;底层的数学算法应该差不多;
动态数组
``
这个没啥可说的,就是一个数组,满了时候,再创建一个数组,把之前的数组里的数据移过来,销毁之前数组;1.
unit Unit4;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Generics.Collections, System.SyncObjs;
type
TForm4 = class(TForm)
btn1: TButton;
btn2: TButton;
procedure btn1Click(Sender: TObject);
procedure btn2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
/// <summary>
/// 定义一个线程
/// </summary>
TGfThread = class(TThread)
protected
procedure Execute; override;
end;
/// <summary>
/// 定义一个线程
/// </summary>
TSfThread = class(TThread)
protected
procedure Execute; override;
end;
TSafeList<T> = class
private
list: TList<T>;
lock: TSpinLock;
public
constructor Create;
destructor Destroy; override;
function Add(const Value: T): NativeInt; inline;
procedure Clear; inline;
end;
var
Form4: TForm4;
listGf: TThreadList<string>;
listSf: TSafeList<string>;
implementation
{$R *.dfm}
procedure TGfThread.Execute;
var
I: Integer;
start: UInt64;
begin
start := GetTickCount;
for I := 0 to 10000 do
begin
listGf.Add(TGUID.NewGuid.ToString);
end;
OutputDebugString(PChar('耗时: ' + (GetTickCount - start).ToString));
end;
procedure TSfThread.Execute;
var
I: Integer;
start: UInt64;
begin
start := GetTickCount;
for I := 0 to 10000 do
begin
listSf.Add(TGUID.NewGuid.ToString);
end;
OutputDebugString(PChar('耗时: ' + (GetTickCount - start).ToString));
end;
procedure TSafeList<T>.Clear;
begin
lock.Enter;
list.Clear;
lock.Exit();
end;
constructor TSafeList<T>.Create;
begin
inherited;
Self.list := TList<T>.Create;
end;
destructor TSafeList<T>.Destroy;
begin
Self.list.Free;
inherited;
end;
function TSafeList<T>.Add(const Value: T): NativeInt;
begin
lock.Enter;
Result := list.Add(Value);
lock.Exit();
end;
procedure TForm4.btn1Click(Sender: TObject);
var
I: Integer;
begin
listGf.Clear;
for I := 0 to 2 do
begin
with TGfThread.Create do
begin
FreeOnTerminate := True;
end;
end;
end;
procedure TForm4.btn2Click(Sender: TObject);
var
I: Integer;
begin
listSf.Clear;
for I := 0 to 2 do
begin
with TSfThread.Create do
begin
FreeOnTerminate := True;
end;
end;
end;
initialization
listGf := TThreadList<string>.Create;
listSf := TSafeList<string>.Create;
ReportMemoryLeaksOnShutdown := True;
finalization
listGf.Free;
listSf.Free;
end.
本文来自博客园,作者:del88,转载请注明原文链接:https://www.cnblogs.com/del88/p/17954193