Monday, 15 June 2015

c - Implementing malloc in multithreaded environment -



c - Implementing malloc in multithreaded environment -

i want implement malloc in multithreaded environment, , got code here.

after adding in mutex:

typedef struct free_block { size_t size; struct free_block* next; pthread_mutex_t lock; } free_block; void free_block_init(free_block *fb){ pthread_mutex_init(&fb->lock, null); } static free_block free_block_list_head = { 0, 0 }; static const size_t overhead = sizeof(size_t); static const size_t align_to = 8; void* mymalloc(unsigned int size) { size = (size + sizeof(size_t) + (align_to - 1)) & ~ (align_to - 1); free_block* block = free_block_list_head.next; pthread_mutex_lock(&block->lock); free_block** head = &(free_block_list_head.next); while (block != 0) { if (block->size >= size) { *head = block->next; pthread_mutex_unlock(&block->lock); homecoming ((char*)block) + sizeof(size_t); } head = &(block->next); block = block->next; } block = (free_block*)sbrk(size); block->size = size; pthread_mutex_unlock(&block->lock); homecoming ((char*)block) + sizeof(size_t); } unsigned int myfree(void* ptr) { free_block* block = (free_block*)(((char*)ptr) - sizeof(size_t)); pthread_mutex_lock(&block->lock); block->next = free_block_list_head.next; free_block_list_head.next = block; pthread_mutex_unlock(&block->lock); }

i'm able allocated memory first block, segmentation fault error. don't know error , i'm new threads , locks, sort of help great! thanks.

in line:

pthread_mutex_lock(&block->lock);

you haven't checked yet whether block null. need locking within loop.

easier still, why not have 1 mutex whole malloc - create static next free_block_list_head can lock @ start of function , unlock after.

if stick per block mutex, remember add together space mutex calculations. need create sure pointer pass pointing memeory after mutex in info structure.

edit: note: haven't called free_block_init anywhere.

c multithreading malloc mutex free

No comments:

Post a Comment