다음은이 질문을 읽은 후 신속하게 구현 한 것입니다.
int mem_block_size;
int mem_block_count;
uint *bit_map;
char *buffer;
void init_memory_map(int block_size, int block_count)
{
mem_block_size = block_size;
mem_block_count = block_count;
buffer = (char*)malloc(block_size * block_count);
bit_map = (uint*)calloc((block_count/32) + ((block_count % 32) != 0), 4);
}
inline
int is_allocated(int index)
{
return (bit_map[index/32] & (1 << (index % 32))) != 0;
}
inline
void allocate_frame(int index)
{
bit_map[index/32] |= 1 << (index % 32);
}
inline
void clear_frame(int index)
{
bit_map[index/32] &= ~(1 << (index % 32));
}
char* allocate_block(int block_count)
{
int index = 0, free_frames = 0;
while(index < mem_block_count)
{
if (!is_allocated(index))
{
free_frames++;
if (free_frames == block_count)
{
int frame_index = index - block_count + 1;
index = 0;
while(index < block_count)
{
allocate_block(frame_index + index);
index++;
}
return (buffer + frame_index * mem_block_size);
}
}
else free_frames = 0;
index++;
}
perror("memory error\n");
return 0;
}
기본적인 아이디어는 할당 된 프레임의 트랙을 유지하는 비트 맵을 유지한다는 것입니다. 각 프레임은 고정 된 크기의 버퍼입니다. 프레임을 완료하면 비트 맵에서 비트를 설정하여 자유롭게 표시 할 수 있습니다.
고맙습니다. 매우 도움이됩니다. 괜찮 으면 몇 가지 질문이 있습니다. 왜 블록 카운트로 귀하의 부서에서 32 개를 선택 했습니까? 각 블록에 32 개의 프레임이 있다고 가정합니까? 또한 왜 네가 4라는 모드를 가지고 있는지 얻지 못했습니까? – Salma
@Salma 내 ** 비트 맵 **이 부호없는 정수 배열로 정의 되었기 때문입니다. 정수는 32 비트를 의미하는 4 바이트를가집니다. 그리고 그 ** 모드 4 ** 나쁜. : p – amaneureka
자세한 내용은 다음과 같습니다. 그 비트 맵은 32 프레임 크기와 관계가없는 정수 배열로 표현 된 비트의 행렬입니다. – amaneureka