Skip to content

Commit

Permalink
[libqueue] up
Browse files Browse the repository at this point in the history
  • Loading branch information
gozfree committed Dec 2, 2018
1 parent 788b2ed commit d297e3d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
24 changes: 22 additions & 2 deletions libqueue/libqueue.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,17 @@

struct item *item_alloc(struct queue *q, void *data, size_t len)
{
if (!q) {
return NULL;
}
struct item *item = CALLOC(1, struct item);
if (!item) {
printf("malloc failed!\n");
return NULL;
}
if (q->alloc_hook) {
item->opaque = (q->alloc_hook)(data, len);
item->opaque.iov_base = (q->alloc_hook)(data, len);
item->opaque.iov_len = len;
} else {
item->data.iov_base = memdup(data, len);
item->data.iov_len = len;
Expand All @@ -42,11 +46,15 @@ struct item *item_alloc(struct queue *q, void *data, size_t len)

void item_free(struct queue *q, struct item *item)
{
if (!q) {
return;
}
if (!item) {
return;
}
if (q->free_hook) {
(q->free_hook)(item->opaque);
(q->free_hook)(item->opaque.iov_base);
item->opaque.iov_len = 0;
} else {
free(item->data.iov_base);
}
Expand All @@ -55,19 +63,28 @@ void item_free(struct queue *q, struct item *item)

int queue_set_mode(struct queue *q, enum queue_mode mode)
{
if (!q) {
return -1;
}
q->mode = mode;
return 0;
}

int queue_set_hook(struct queue *q, alloc_hook *alloc_cb, free_hook *free_cb)
{
if (!q) {
return -1;
}
q->alloc_hook = alloc_cb;
q->free_hook = free_cb;
return 0;
}

int queue_set_depth(struct queue *q, int depth)
{
if (!q) {
return -1;
}
q->max_depth = depth;
return 0;
}
Expand All @@ -92,6 +109,9 @@ struct queue *queue_create()

int queue_flush(struct queue *q)
{
if (!q) {
return -1;
}
struct item *item, *next;
pthread_mutex_lock(&q->lock);
list_for_each_entry_safe(item, next, &q->head, entry) {
Expand Down
5 changes: 3 additions & 2 deletions libqueue/libqueue.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,13 @@ enum queue_mode {
struct item {
struct iovec data;
struct list_head entry;
void *opaque;
struct iovec opaque;
};

typedef void *(alloc_hook)(void *data, size_t len);
typedef void (free_hook)(void *data);


struct queue {
struct list_head head;
int depth;
Expand All @@ -59,12 +60,12 @@ void item_free(struct queue *q, struct item *item);
struct queue *queue_create();
void queue_destroy(struct queue *q);
int queue_set_depth(struct queue *q, int depth);
int queue_get_depth(struct queue *q);
int queue_set_mode(struct queue *q, enum queue_mode mode);
int queue_set_hook(struct queue *q, alloc_hook *alloc_cb, free_hook *free_cb);
struct item *queue_pop(struct queue *q);
int queue_push(struct queue *q, struct item *item);
int queue_flush(struct queue *q);
int queue_get_depth(struct queue *q);

#ifdef __cplusplus
}
Expand Down

0 comments on commit d297e3d

Please sign in to comment.