Buffer queue classes for fixed-size memory blocks and C + + implementation source code

Source: Internet
Author: User
Tags lock queue

--------------------------------------------------------------------------------
Title: Buffer Queue class for fixed-size memory blocks and implementation source code
Author: Ye Feihu
Date: 2014.10.21
--------------------------------------------------------------------------------

In general linear operation applications (e.g. receive buffers), it may be necessary to allocate and free memory blocks frequently,
The system will be very expensive, how to reduce the system overhead? Reduce the operation by pulling the spacing between the distribution and the release
To reduce system overhead.

There are many ways to pull the gap between allocations and releases, which can be managed by a large memory block, or through memory
Block buffer queue.

This article focuses on the memory block buffer queue, involving the queue will take into account the non-lock in and out of the queue, that is, into the queue and
The out queue can operate at the same time in two threads.

There are many ways to implement a lock-free queue, and there are arrays of rings without locking teams
Column, there is also a link to the lock-free queue.

Array mode is more appropriate when the queue capacity is determined, and the linking method is more suitable for
The capacity of the queue is variable, and the applicability is better.

Array mode lock-free queue See my Blog < How does a lock-free ring queue be implemented under one-read-write limit? >
Link mode no lock queue see my blog post < First read the case. How does a lock-free queue be implemented? >

This article is about the buffer team as a link, the link is generally by pre-allocation of a node as a relay point to achieve No
Lock queue, the advantage is simple implementation, the disadvantage is to waste a node of memory, when the node memory block size is large waste
The How to not waste a node memory link way without lock queue? When there is only one node in the queue, this buffer queue
The use of atomic locks in the operation, this is a balance strategy, if the reader has a better way is best to sue the next!

The Buffer queue Class (Tkycache) source code for fixed-size memory blocks is as follows:

=======================================//Unit: Fixed-size memory block buffer//version:3.0.0.0 (build 2014.10.21)//Author:kyee Ye/ /Email:kyee_ye (at) 126.com//Copyright (C) kyee workroom//======================================= #ifndef _KYCache_H_ #define _KYCACHE_H_#INCLUDE "KYObject.h"//kylib 2.0 start using Kylib namespace namespace kylib{//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~/* tkycache-Fixed size memory block buffer class *///Note://1. For multi-thread access security, the new and delete sub-two threads can operate at the same time without the need to lock,//But the multi-threaded New must be controlled with a lock, multi-threaded Delete must be controlled with a lock!//2.                This buffer class is generally applied to classes in linear operations to reduce the buffering usage of frequently allocated and freed memory. Class Tkycache{private://memory block link typedef struct {void* self;                Memory block belongs to Object void* Next; Next block} tlink, *plink;public://constructor//1. Ablocksize The fixed size of the memory block, the range of values: [0x40. 0X40000000]//2.   Amaxcount the maximum number of memory block buffers Tkycache (long ablocksize = 1024x768, long amaxcount = 256);   Virtual ~tkycache (); Attribute Long Count () const {return FPUSHCOUNT-FPOpcount;   } long MaxCount () const {return fmaxcount;}  Default:amaxcount long BlockSize () const {return fblocksize;} Default:ablocksize//Set maximum number of memory block buffers void Setmaxcount (long amaxcount) {Fmaxcount = (AMax Count >= 0)? amaxcount:0;                     }//Allocate a fixed-size memory block void* New () {tlink* pitem = donew (); Return (Pitem! = NULL)?

(char*) Pitem + sizeof (tlink): NULL; }//Release fixed-size memory block void Delete (void* ablock) {if (Ablock! = NULL) {tlink* Pitem = (tlink*) ((char*) ablock-sizeof (Tlink)); if (pitem->self = = this) DoDelete (Pitem); }}private://Run allocate/release memory block with link tlink* donew (); void DoDelete (tlink* ALink); Run purge buffer queue void Doclear (tlink* AHead);p rivate:tlink* fhead; Buffered head links tlink* Ftail; Buffered tail link long fflag; Buffer queue flag long fmaxcount; Buffer maximum number of long fblocksize; The size of the memory block Longword Fpushcount; Press-in buffer count Longword Fpopcount; Popup buffer count};} #endif


=======================================//Unit: Fixed-size memory block buffer//version:3.0.0.0 (build 2014.10.21)//Author:kyee Ye/ /Email:kyee_ye (at) 126.com//Copyright (C) kyee workroom//======================================= #include <malloc .h> #include "KYCache.h"//kylib 2.0 start using Kylib namespace namespace kylib{//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~/* tkycache-Fixed-size memory block buffer class *///----------------constructors and destructors----------------//   Constructor Tkycache::tkycache (long ablocksize, long Amaxcount) {//Initialize fhead = NULL;   Ftail = NULL;   Fflag = 0;   Fpushcount = 0;   Fpopcount = 0; Set the maximum number of buffers Fmaxcount = (amaxcount >= 0)?   amaxcount:0;   Sets the size of the memory block if (ablocksize <= 0x40) fblocksize = 0x40;   else if (ablocksize <= 0x40000000) fblocksize = ablocksize; else fblocksize = 0x40000000;}      destructor Tkycache::~tkycache () {//Run purge buffer queue if (fpopcount! = fpushcount) {fpopcount = Fpushcount; DocleAR (Fhead); }}//----------------Private Function----------------//Run allocate memory block with link tkycache::tlink* tkycache::D onew () {//Initialize tlink* result = NU   LL;   Infers if the buffer queue is empty if (Fpopcount = = Fpushcount) result = (tlink*) malloc (sizeof (Tlink) + fblocksize);      else if (fpushcount-fpopcount! = 1) {//Take first item, and count plus 1 result = Fhead;      Fhead = (tlink*) result->next;   fpopcount++;      } else {//take the first result = Fhead;         Infer if there is a need to wait to prevent DoDelete conflict if (interlockedincrement (&fflag) = = 1) {fpopcount++;            if (Fpopcount = = fpushcount) {fhead = NULL;         Ftail = NULL;      } interlockeddecrement (&fflag);         } else {fpopcount++;         InterlockedDecrement (&fflag);      The loop waits for Fpushcount change while (Fpopcount = = Fpushcount) Sleep (1);   }//Change the buffered Header link if (result->next! = NULL) Fhead = (tlink*) result->next; }//Initialize the link item if (ResULt! = NULL) {result->self = this;   Result->next = NULL; }//Returns the result of return results;}      Run free memory block with link void Tkycache::D odelete (tlink* ALink) {//infer if full if (Fpushcount-fpopcount >= (longword) fmaxcount)   Free (ALink);      else {//empty alink->next = null; The reference count plus 1, if not equal to 1, waits for donew to become 1 if (InterlockedIncrement (&fflag)! = 1) while (Fflag! = 1) Sl      EEP (0);         Infers if the first item if (Ftail = = NULL) {ftail = ALink;      Fhead = ALink;         } else {ftail->next = ALink;      Ftail = ALink;      }//Count plus 1, and reference count minus 1 (note: The order can not be changed, otherwise it may lead to donew dead Loop) fpushcount++;   InterlockedDecrement (&fflag);   }}//run purge buffer queue void Tkycache::D oclear (tlink* AHead) {//Initialize void* Pcurr;      Loop release while (AHead! = NULL) {Pcurr = AHead;      AHead = (tlink*) ahead->next;   Release free (PCURR); }}}

--------------------------------------------------------------------------------

Buffer queue classes for fixed-size memory blocks and C + + implementation source code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.