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();
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();