我正在尝试在C中实现一个无锁链接列表,并使其可以使用create
实例化无锁链表的多个实例代码如下:
typedef struct node_s node_t;
struct node_s {
node_t *next;
void *data;
uint32_t tag;
};
typedef struct list_s list;
struct list_s
{
node_t *head;
node_t *tail;
};
list *create_queue(void){
list* _list =NULL;
_list = (list*)malloc(sizeof(list));
node_t *head = NULL;
node_t *tail = NULL;
head = (node_t*)malloc(sizeof(node_t));
if (!head) {
fprintf(stderr, "malloc error\n");
return NULL;
}
head->next = NULL;
head->data = NULL;
tail = head;
_list->head = head;
_list->tail = head;
return _list;
}
node_t* enqueue(void *d, list *_list)
{
if (_list == NULL)
{
fprintf(stderr, "List error\n");
return NULL;
}
node_t *p = (node_t*)malloc(sizeof(node_t));
if (!p) {
fprintf(stderr, "malloc error\n");
return NULL;
}
p->next = NULL;
p->data = d;
node_t *q;
do {
q = &_list->tail;
} while (!__sync_bool_compare_and_swap(&(q->next), NULL, p));
__sync_bool_compare_and_swap( &(_list->tail), q, p);
return p;
}
void* dequeue(list *_list)
{
node_t *p;
void *res;
if (_list ==NULL)
{
fprintf(stderr, "List error\n");
return NULL;
}
do {
p = _list->head;
if (p->next == NULL){
return NULL;
}
res = p->next->data;
} while(!__sync_bool_compare_and_swap(&_list->head, p, p->next));
if (p) {
free(p);
p = NULL;
}
return res;
}
问题在于,当我尝试使用enqueue然后随后出列时,它会出现分段错误。所以,如果你能指出那个有很大帮助的问题。
任何帮助将不胜感激。