PDA

View Full Version : fast connections management with que, source code


emihaly
04-07-2003, 11:52 AM
Situation:

Server in one thread /unblocking accept/ accept connections and put it to array of data example: socket, buffer, int size, int index. If we have prepared 5000 struct slots for 5000 connections, and when we have 4500 connections active, we must always search free empty slot for new connection in cycle like for(;;i<5000) if (flag == free we have it!) else full.

But it take 4*4500 ints(4 byte) = 72 kB!!! in one cycle!!! in freq 100 times per seconds result is 7,2 MB wasted mem i/o & cpu actions on server!

Solution is use fast que which have index with next free position. Here is nice example:

// FREE_SLOT - maximum number of connections
// InitQue(); fill max free connections
// AddToQue(); Add connection which was closed
// GetFromQue(); get free position

#define FREE_SLOT 3

struct Que
{
int item[FREE_SLOT];
int count;
inline void InitQue();
inline void AddToQue(int data);
inline int GetFromQue();
}
*que_pntr ;

inline void Que::InitQue()
{
count = FREE_SLOT;
for (int i = 0; i < FREE_SLOT; i++ ) item[i] = FREE_SLOT-i-1;
}

inline int Que::GetFromQue()
{
if ( count == 0 ) return -1;
return item[--count];
}

inline void Que::AddToQue(int data)
{
if (count < FREE_SLOT) item[count++] = data;
}


usage:

int gt;
Que *block =new Que;
block->InitQue();

gt=block->GetFromQue();
gt=block->GetFromQue();
gt=block->GetFromQue();

block->AddToQue(0);
block->AddToQue(1);
block->AddToQue(2);

gt=block->GetFromQue();
gt=block->GetFromQue();
gt=block->GetFromQue();

x33
04-08-2003, 11:01 PM
Hmm... i would rather use one of the std tools... std::vector, std::queue or std::map (depends on the type of the application). The c++ standart template library provides powerful, flexible and effective solutions to use. I believe stl is as fast as possible (it was developed by hundreds of smart people).

emihaly
04-09-2003, 01:04 PM
Yes, but this is for standard c too, and stl is c++. also this solution is faster and better for memory consumation.
:!:

Loco
05-10-2003, 10:05 PM
Eduard,

What is the point of this subject???

I don't see the difference between what you are doing and just keeping a simple variable that says how much free space you have.

BTW, what you have written here behaves as a stack, not as a queue. You are pushing at the end of the list and poping from the end of the list.

I think the better approach would be to create a double linked list (if you manage too much fixed information, but the list doesn't grow/shrink too much), or maybe a dynamic vector that doubles its size after some threshold.

Can you explain the purpose of this code???