无锁队列和指针困境

时间:2012-08-24 02:51:24

标签: c windows synchronization

我被要求使用比较和交换在c中实现无锁队列,但是我对指针的了解非常有限。

我一直在使用以下代码来测试我的(尚未完成)dequeue实现,但我相信它是无限循环的,因为我不太确定如何正确使用指针/运算符地址。

我已经使用了这个CAS函数,因为我对汇编程序一无所知。

long __cdecl compare_exchange(long *flag, long oldvalue, long newvalue)
{
    __asm
    {
        mov ecx, flag
        mov eax, oldvalue
        mov ebx, newvalue
        lock cmpxchg [ecx], ebx
        jz iftrue
    }
    return 0;
    iftrue: return 1;
}

我目前的(相关)代码如下......

typedef struct QueueItem
{
    int data;
    struct QueueItem* next;
}item;

struct Queue
{
    item *head;
    item *tail;
}*queue;

int Dequeue()
{
    item *head;

    do
    {
        head = queue->head;
        if(head == NULL)
            return NULL_ITEM;
        printf("%d, %d, %d\n", (long *)queue->head, (long)&head, (long)&head->next);
    }
    while(!compare_exchange((long *)queue->head, (long)&head, (long)&head->next)); // Infinite loop.

    return head->data;
}

int main(int argc, char *argv[])
{
    item i, j;

    queue = (struct Queue *) malloc(sizeof(struct Queue));

    // Manually enqueue some data for testing dequeue.
    i.data = 5;
    j.data = 10;
    i.next = &j;
    j.next = NULL;

    queue->head = &i;

    printf("Dequeued: %d\n", Dequeue());
    printf("Dequeued: %d\n", Dequeue());
}

我应该在do while循环中使用not运算符吗?如果我不使用该运算符,我会得到“Dequeued 5”x2的输出,这表明交换没有发生,我应该使用not。如果是的话,我哪里错了?我把钱作为指针/地址操作员的问题。

1 个答案:

答案 0 :(得分:0)

指针和值存在混淆。这是更正后的代码:

 do
 {
    head = queue->head;
    if(head == NULL)
        return 0;
    printf("%d, %d, %d %d\n", (long *)queue->head, (long)head, (long)head->next, head->data);
  }  while (!compare_exchange((long *)&queue->head,   (long)head, (long)head->next));

你试图写出head-> head指向的是什么,而不是queue-> head本身的值。

此外,为了使其在多核上正常工作,我认为你需要将头部定义为易失性。

struct Queue
{
   volatile item *head;
   item *tail;
}*queue;
相关问题