一个简易无锁池

一个简易 无锁池

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.mzph.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;不然又要头疼或者成为问题的瓶颈了。 …