单线程执行任务和无锁链表

#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <pthread.h>


#define offsetof(type, member) (size_t)&(((type *)(0))->member)
#define contain_of(ptr, type, member) (type *)((*(size_t *) &ptr) - offsetof(type, member)


typedef void (*fn_t)(int, char **);

struct list {
    struct list *next;
};

struct list_cnt {
    struct list root;
    struct list **tail;
};

typedef struct task_queue {
    int argc;
    char **argv;
    fn_t fn;
    struct list node;
} task_queue_t;


static void put(struct list_cnt *head, struct list *node) {
    node->next = NULL;
    struct list **ptr = __sync_lock_test_and_set(&head->tail, &node->next);
    *ptr = node;
}

static struct list *get(struct list_cnt *root) {
    struct list *head = __sync_lock_test_and_set(&root->root.next, NULL);
    if (head == NULL) {
        return NULL;
    }
    struct list *next = head->next;
    if (next != NULL) {
        root->root.next = next;
        head->next = head;
        return head;
    }
    int b = __sync_bool_compare_and_swap(&root->tail, &head->next, &root->root.next);
    if (b) {
        head->next = head;
        return head;
    }
    root->root.next = head;
    return NULL;
}

void task(int argc, char **argv) {
    printf("argc = %d, **argv = %d\n", argc, **argv);
    free(*argv);
    free(argv);
}

void test(struct list_cnt *head) {
    int i = 0;
    for (i = 0; i < 10; i++) {
        task_queue_t *queue = malloc(sizeof(task_queue_t));
        queue->argc = 1;
        queue->argv = malloc(sizeof(int *));
        *queue->argv = malloc(sizeof(int *));
        **queue->argv = i;
        queue->fn = task;
        put(head, &queue->node);
    }
}

void *do_task(void *arg) {
    struct list_cnt *head = (struct list_cnt *)arg;
    for (;;) {
        struct list *tmp = NULL;
        while ((tmp = get(head)) == NULL) {
            poll(NULL, 0, 100);
        }
        task_queue_t *task = contain_of(tmp, task_queue_t, node);
        task->fn(task->argc, task->argv);
        free(task);
    }
    return NULL;
}

int main(int argc, char *argv[]) {
    struct list_cnt head = {{NULL}, &(head.root.next)};
    pthread_t thid;
    pthread_create(&thid, NULL, do_task, &head);
    test(&head);
    for(;;);
    return EXIT_SUCCESS;
}

无锁链表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值