feat(heap): thread-safety features

min-heap
Jef Roosens 2023-01-27 20:59:06 +01:00
parent d77b3e4fee
commit 5b2ce6acaa
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
4 changed files with 41 additions and 3 deletions

View File

@ -11,7 +11,7 @@ typedef enum vieter_heap_error {
} vieter_heap_error; } vieter_heap_error;
/* /*
* Allocate and initalize an empty heap. * Allocate and initialize an empty heap.
*/ */
vieter_heap *vieter_heap_init(); vieter_heap *vieter_heap_init();
@ -41,4 +41,22 @@ vieter_heap_error vieter_heap_pop(void **out, vieter_heap *heap);
*/ */
vieter_heap_error vieter_heap_peek(void **out, vieter_heap *heap); vieter_heap_error vieter_heap_peek(void **out, vieter_heap *heap);
/*
* Acquire a read lock on the heap. Return value is the result of
* pthread_rwlock_rdlock.
*/
int vieter_heap_rlock(vieter_heap *heap);
/*
* Acquire a write lock on the heap. Return value is the result of
* pthread_rwlock_wrlock.
*/
int vieter_heap_wlock(vieter_heap *heap);
/*
* Unlock the lock after having acquired it. Return value is the result of
* pthread_rwlock_unlock.
*/
int vieter_heap_unlock(vieter_heap *heap);
#endif #endif

View File

@ -2,7 +2,13 @@
#include <stdlib.h> #include <stdlib.h>
vieter_heap *vieter_heap_init() { return calloc(1, sizeof(vieter_heap)); } vieter_heap *vieter_heap_init() {
vieter_heap *heap = calloc(1, sizeof(vieter_heap));
pthread_rwlock_init(&heap->lock, NULL);
return heap;
}
uint64_t vieter_heap_size(vieter_heap *heap) { uint64_t vieter_heap_size(vieter_heap *heap) {
uint64_t size = 0; uint64_t size = 0;
@ -76,3 +82,15 @@ vieter_heap_error vieter_heap_peek(void **out, vieter_heap *heap) {
return vieter_heap_ok; return vieter_heap_ok;
} }
int vieter_heap_rlock(vieter_heap *heap) {
return pthread_rwlock_rdlock(&heap->lock);
}
int vieter_heap_wlock(vieter_heap *heap) {
return pthread_rwlock_wrlock(&heap->lock);
}
int vieter_heap_unlock(vieter_heap *heap) {
return pthread_rwlock_unlock(&heap->lock);
}

View File

@ -1,6 +1,8 @@
#include "vieter_heap.h" #include "vieter_heap.h"
#include "vieter_heap_tree.h" #include "vieter_heap_tree.h"
#include <pthread.h>
struct vieter_heap { struct vieter_heap {
vieter_heap_node *tree; vieter_heap_node *tree;
pthread_rwlock_t lock;
}; };

View File

@ -18,7 +18,7 @@ typedef struct vieter_heap_node {
} vieter_heap_node; } vieter_heap_node;
/* /*
* Allocate an initialize a heap node object. * Allocate and initialize a heap node object.
*/ */
vieter_heap_node *vieter_heap_node_init(); vieter_heap_node *vieter_heap_node_init();