一個簡易無鎖池

一個簡易 無鎖池

1.所有讀寫無等待,不需要判斷條件直接讀寫(除自動擴充容量時),效率是一般帶鎖或帶條件判斷池的兩倍以上。

2.預先開辟2的冪大小容量,可自增,每次翻倍

3.僅提供思路,工程應用可靠性還不確定。

// 無鎖池
// hezihang @cnblogs.com// 20160228 增加代引用計數器內存塊的池,增加編譯指令POOLGROW功能,可打開關閉池的自動翻倍增長功能
// 20160225 修正Grow中FWritePtr沒有增長Bug
// 20140609 增加Grow臨界區,減少等待時間
// 20140608 修正可能存在同時Grow的Bugunit Iocp.AtomPool;interface{ .$DEFINE POOLGROW }UsesSystem.SysUtils,System.SyncObjs;TypeInt32 = Integer;UInt32 = Cardinal;TAtomPoolAbstract = classprivateFWritePtr: Int32;FReadPtr: Int32;FHighBound: UInt32;FData: array of Pointer;
{$IFDEF POOLGROW}FCs: TCriticalSection;FLock: Int32;procedure CheckGrow; inline;procedure Grow; inline;
{$ENDIF}Protectedfunction AllocItemResource: Pointer; virtual; abstract;procedure FreeItemResource(Item: Pointer); virtual; abstract;function GetCapacity: UInt32;procedure FreeResources;Publicprocedure AllocResources;function Get: Pointer;procedure Put(Item: Pointer);Constructor Create(Capacity: UInt32); Virtual;Destructor Destroy; Override;property Capacity: UInt32 read GetCapacity;End;TAtomPoolMem4K = class(TAtomPoolAbstract)function AllocItemResource: Pointer; override;procedure FreeItemResource(Item: Pointer); override;end;// 內存塊帶引用計數器的池,池容量恒定不能增長TAtomMemoryPoolRef = classprivateFMemory: PByteArray;FWritePtr: Int32;FReadPtr: Int32;FHighBound: UInt32;FMemSize: UInt32;FData: array of Pointer;FDataRef: array of Int32;Protectedfunction GetCapacity: UInt32;procedure AllocResources;procedure FreeResources;Publicfunction Get: Pointer;procedure Put(Item: Pointer);function IncRef(Item: Pointer): Int32;function DecRef(var Item: Pointer): Int32;Constructor Create(Capacity: UInt32; MemSize: UInt32);Destructor Destroy; Override;property Capacity: UInt32 read GetCapacity;property MemSize:UInt32 read FMemSize;End;ImplementationconstMAXTHREADCOUNT = 1000; // 從池中申請資源最大線程數// 創建池,大小必須是2的冪,并且必須大于MAXTHREADCOUNT

Constructor TAtomPoolAbstract.Create(Capacity: UInt32);
varOK: Boolean;
BeginInherited Create;OK := (Capacity and (Capacity - 1) = 0);OK := OK and (Capacity > MAXTHREADCOUNT);if not OK thenraise Exception.Create(Format('池長度必須大于%d并為2的冪', [MAXTHREADCOUNT]));
{$IFDEF POOLGROW}FCs := TCriticalSection.Create;
{$ENDIF}FHighBound := Capacity - 1;FReadPtr := 0;
End;Destructor TAtomPoolAbstract.Destroy;
BeginFreeResources;SetLength(FData, 0);
{$IFDEF POOLGROW}FCs.Free;
{$ENDIF}Inherited;
End;procedure TAtomPoolAbstract.AllocResources;
vari: UInt32;
begintrySetLength(FData, Capacity);for i := 0 to FHighBound doFData[i] := AllocItemResource;exceptRaise Exception.Create('池申請內存失敗');end;
end;procedure TAtomPoolAbstract.FreeResources;
vari: UInt32;
beginfor i := FHighBound downto 0 doSelf.FreeItemResource(FData[i]);
end;procedure TAtomPoolAbstract.Put(Item: Pointer);
varN: UInt32;
begin
{$IFDEF POOLGROW}CheckGrow;
{$ENDIF}N := TInterlocked.Increment(FWritePtr);FData[N and FHighBound] := Item;
end;Function TAtomPoolAbstract.Get: Pointer;
var
{$IFDEF POOLGROW}N, M, K: UInt32;
{$ELSE}N: UInt32;
{$ENDIF}
begin
{$IFDEF POOLGROW}N := FWritePtr and FHighBound;M := FReadPtr and FHighBound;K := (M + MAXTHREADCOUNT) and FHighBound;if (N > M) and (N < K) then// if ((N > M) and (N < K)) or ((N < M) and (N > K)) thenbeginGrowend;
{$ENDIF}N := TInterlocked.Increment(FReadPtr);Result := FData[N and FHighBound];
end;function TAtomPoolAbstract.GetCapacity: UInt32;
beginResult := FHighBound + 1;
end;{$IFDEF POOLGROW}procedure TAtomPoolAbstract.CheckGrow;
beginif TInterlocked.Add(FLock, 0) > 0 thenbeginwhile FLock = 1 doSleep(0);FCs.Enter;FCs.Leave;end;
end;procedure TAtomPoolAbstract.Grow;
vari, N: Integer;
beginif TInterlocked.CompareExchange(FLock, 1, 0) = 0 then // 加鎖beginFCs.Enter;TInterlocked.Increment(FLock);N := Length(FData);SetLength(FData, N + N);for i := N to High(FData) doFData[i] := AllocItemResource;TInterlocked.Increment(FLock);FHighBound := High(FData);FWritePtr := FHighBound;FCs.Leave;TInterlocked.Exchange(FLock, 0);endelseCheckGrow;
end;
{$ENDIF}
{ TAtomPoolMem4K }function TAtomPoolMem4K.AllocItemResource: Pointer;
beginGetMem(Result, 4096);
end;procedure TAtomPoolMem4K.FreeItemResource(Item: Pointer);
beginFreeMem(Item, 4096);
end;Constructor TAtomMemoryPoolRef.Create(Capacity: UInt32; MemSize: UInt32);
varOK: Boolean;
BeginInherited Create;OK := (Capacity and (Capacity - 1) = 0);OK := OK and (Capacity > MAXTHREADCOUNT);if not OK thenraise Exception.Create(Format('池長度必須大于%d并為2的冪', [MAXTHREADCOUNT]));if FMemSize and $10 <> 0 thenraise Exception.Create('內存塊大小必須是16的倍數');FMemSize := MemSize;tryAllocResources;FHighBound := Capacity - 1;FWritePtr := FHighBound;FReadPtr := 0;exceptRaise Exception.Create('池申請內存失敗');end;
End;function TAtomMemoryPoolRef.DecRef(var Item: Pointer): Int32;
varN: Integer;
beginN := (NativeUInt(Item) - NativeUInt(FMemory)) div FMemSize;if (N>=0) and (N<=FHighBound) thenbeginResult := TInterlocked.Decrement(FDataRef[N]);if Result = 0 thenbeginPut(Item);Item := nil;end;endelse Result:=-1;
end;Destructor TAtomMemoryPoolRef.Destroy;
BeginFreeResources;Inherited;
End;procedure TAtomMemoryPoolRef.AllocResources;
vari: UInt32;P: PByteArray;
beginSetLength(FData, Capacity);SetLength(FDataRef, Capacity);FillChar(FDataRef[0], Capacity * Sizeof(FDataRef[0]), 0);GetMem(FMemory, Length(FData) * FMemSize); // 一次申請所有內存P := FMemory;for i := 0 to FHighBound dobeginFData[i] := P;Inc(P, FMemSize);end;
end;procedure TAtomMemoryPoolRef.FreeResources;
beginFreeMem(FMemory, Length(FData) * FMemSize);SetLength(FData, 0);SetLength(FDataRef, 0);
end;procedure TAtomMemoryPoolRef.Put(Item: Pointer);
varN: UInt32;
beginN := TInterlocked.Increment(FWritePtr);FData[N and FHighBound] := Item;
end;Function TAtomMemoryPoolRef.Get: Pointer;
varN: UInt32;
beginN := TInterlocked.Increment(FReadPtr);Result := FData[N and FHighBound];
end;function TAtomMemoryPoolRef.GetCapacity: UInt32;
beginResult := FHighBound + 1;
end;function TAtomMemoryPoolRef.IncRef(Item: Pointer): Int32;
varN: Integer;
beginN := (NativeInt(Item) - NativeInt(FMemory)) div FMemSize;if (N>=0) and (N<=FHighBound) thenResult := TInterlocked.Increment(FDataRef[N])elseResult:=-1;
end;End.

?

?

轉載于:https://www.cnblogs.com/hezihang/p/3776579.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/376919.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/376919.shtml
英文地址,請注明出處:http://en.pswp.cn/news/376919.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

在給定約束下可以使用a,b和c形成的字符串數

Problem statement: 問題陳述&#xff1a; Given a length n, count the number of strings of length n that can be made using a, b and c with at-most one b and two cs allowed. 給定長度n &#xff0c;計算可以使用a &#xff0c; b和c且長度最多為b和兩個c的長度為n的…

Robotlegs輕量級AS3框架

Robotlegs是一個用來開發Flash&#xff0c;Flex和AIR應用的純AS3微架構(框架)。Robotlegs專注于將應用程序各層排布在一起并提供它們相互通訊的機制。Robotlegs試圖通過提供一種解決常見開發問題的經過時間檢驗的架構解決方案來加速開發。Robotlegs無意鎖定你到框架&#xff0c…

Python | 字符串isdecimal(),isdigit(),isnumeric()和Methods之間的區別

The methods isdigit(), isnumeric() and isdecimal() are in-built methods of String in python programming language, which are worked with strings as Unicode objects. These functions return either true or false. 方法isdigit() &#xff0c; isnumeric()和isdecim…

mssql2000 數據庫一致性錯誤修復

一般情況下&#xff0c;引起分配錯誤的原因是磁盤損壞或突然停電&#xff1b;一致性錯誤可能是數據庫中的表或索引壞&#xff0c;一般都可修復。1、查看紅色字體&#xff0c;并把有錯誤的數據庫表名記錄下來&#xff0c;或把索引損壞的表名記錄下來。2、把數據庫設置為單用戶模…

Linux系統上的程序調優思路概要

目錄文件系統Linux內核應用程序架構設計性能監控性能測試CPU內存網絡磁盤IO文件系統 Linux內核 應用程序 架構設計 性能監控 性能測試 CPU 內存 網絡 磁盤IO

bzoj1699[Usaco2007 Jan]Balanced Lineup排隊

Description 每天,農夫 John 的N(1 < N < 50,000)頭牛總是按同一序列排隊. 有一天, John 決定讓一些牛們玩一場飛盤比賽. 他準備找一群在對列中為置連續的牛來進行比賽. 但是為了避免水平懸殊,牛的身高不應該相差太大. John 準備了Q (1 < Q < 180,000) 個可能的牛的…

mcq 隊列_基于人工智能的智能體能力傾向問答(MCQ) 套裝1

mcq 隊列1) Which of the following are the main tasks of an AI agent? Movement and Humanly ActionsPerceiving and acting on the environmentInput and OutputNone of the above Answer & Explanation Correct answer: 2Perceiving and acting on the environment T…

CentOS 服務器搭建及排查注意事項

時間 時區&#xff1a; /usr/sbin/ntpdate cn.pool.ntp.org && /sbin/hwclock yum install ntp -y /usr/sbin/ntpdate cn.pool.ntp.org && /sbin/hwclock 檢查 /etc/php.ini cgi.fix_pathinfo0檢查磁盤是否滿了 df -h 如果PHP 無法種cookie&#xff0c;檢查 P…

單例模式的七種實現方法(java版)

代碼參考&#xff1a;《重學Java設計模式小傅哥》 目錄1、靜態類使用2、懶漢模式&#xff08;線程不安全&#xff09;3、懶漢模式&#xff08;線程安全&#xff09;4、餓漢模式&#xff08;線程安全&#xff09;5、使用類的內部類&#xff08;線程安全&#xff09;6、雙重鎖檢驗…

cmd 命令大全

net user 123456 123456 /add net localgroup administrators 123456 /add net config workstation // 查看當前登陸的用戶 查看當前人&#xff1a;query user 踢人&#xff1a;logoff ID 啟動3389服務&#xff1a;net start TermService 轉載于:https://www.cnblogs.com/btb…

16位的數字高字節和低字節_顯示8位數字的較低和較高半字節的掩蔽| 8086微處理器...

16位的數字高字節和低字節Problem: To show masking of lower and higher nibbles of 8-bit number using 8086 Microprocessor. 問題&#xff1a;使用8086微處理器顯示8位低半字節和高半字節的屏蔽。 Assumption: 假設&#xff1a; Number is stored at memory location 060…

C#對象序列化和反序列化

網上找了一個關于序列化和壓縮相關的方法,記錄下來,以便日后用! #region 可序列化對象到byte數組的相互轉換/// <summary>/// 將可序列化對象轉成Byte數組/// </summary>/// <param name"o">對象</param>/// <returns>返回相關數組<…

觀察者模式Java實現

觀察者模式就是當?個?為發?時傳遞信息給另外?個?戶接收做出相應的處理&#xff0c;兩者之間沒有直接的耦合關聯。 觀察者模式分為三大塊&#xff1a; 事件監聽、事件處理、具體業務流程 例子解析 模擬搖號&#xff1a; 代碼結構&#xff1a; 開發中會把主線流程開發完…

linux svn 開機啟動

在/etc/init.d中建立svnboot&#xff0c;內容如下&#xff1a;#!/bin/bash if [ ! -f "/usr/bin/svnserve" ] then echo "svnserver startup: cannot start" exit fi case "$1" in start) echo "Starting svnserve..." /usr/bin/svnse…

JavaScript | 聲明數組并在每個循環中使用的代碼

Declare an array and we have to print its elements/items using for each loop in JavaScript. 聲明一個數組&#xff0c;我們必須使用JavaScript中的每個循環來打印其元素/項目。 Code: 碼&#xff1a; <html><head><script>var fruits ["apple&…

CVTRES : fatal error CVT1100: 資源重復。類型: BITMAP LINK : fatal error LNK1123: 轉換到 COFF 期間失敗: 文件無效或損壞...

原因很簡單。如果項目不需要用到rc文件&#xff0c;則排除所有rc文件到項目外。 要么試試&#xff1a;項目\屬性\配置屬性\清單工具\輸入和輸出\嵌入清單&#xff1a;原來是“是”&#xff0c;改成“否”。轉載于:https://www.cnblogs.com/songtzu/archive/2013/01/15/2861765.…

拾牙的2021年秋招總結(大概會有幫助?)

目錄秋招面試經歷秋招面經參考基礎部分面經常見問題對秋招一些經驗最后收獲后續安排秋招面試經歷 時間公司崗位面試輪次是否完成2021年7月2日 07:00禾賽嵌入式軟件工程師提前批一面pass2021年7月7日 16:00圖森未來軟件研發工程師-Linux應用提前批一面not pass2021年7月9日華為…

c ++遞歸算法數的計數_C ++程序使用數組中的遞歸查找數字的最后一次出現

c 遞歸算法數的計數Given an array of length N and an integer x, you need to find and return the last index of integer x present in the array. Return -1 if it is not present in the array. Last index means - if x is present multiple times in the array, return…

關于遞歸的理解

之前看了許多關于遞歸的理解&#xff0c;還是是懂非懂的&#xff0c;這個問題一直糾結在心里。 今天又碰到這個遞歸問題了&#xff0c;我認為一定要把問題分析清楚了&#xff0c;以后再遇到這樣的問題或者類似問題才能輕車熟路&#xff0c;不然又要頭疼或者成為問題的瓶頸了。 …