Lock-free queue

后端 未结 5 1262
醉话见心
醉话见心 2021-01-01 07:35

\"enter \"enter

5条回答
  •  长发绾君心
    2021-01-01 08:19

    (Leaving this here for now, but see edit.)

    Do you know a implementation of lock free queue in C?

    I wrote lockless queue recently (http://www.ideone.com/l2QRp). I can't actually guarantee it works correctly, but I can't find any bugs and I've used it in a couple of single threaded programs without any problems, so there's nothing too obvious wrong with it.

    Trivial usage example:

    queue_t queue;
    int val = 42;
    queue_init(&queue,sizeof val);
    queue_put(&queue,&val);
    val = 0; 
    queue_pop(&queue,&val);
    printf("%i\n",val); // 42
    queue_destroy(&queue);
    

    Edit:

    As @Alexey Kukanov pointed out, queue_pop can fail if tmp is popped,freed,allocated again, and put again between checking for null and swapping:

        if(!tmp->next) return errno = ENODATA;
        /* can fail here */
        } while(!sync_swap(q->head,tmp,tmp->next));
    

    I'm not yet sure how to fix this, but I'll (hopefully) update this once I figure it out. For now, disregard this.

提交回复
热议问题