将结构传递给用于原子访问的gcc内置函数

时间:2015-06-07 20:47:44

标签: c++ multithreading atomic

我有两个结构,如下所示:

template <class T>
struct pointer_t
{
    T *ptr;
    uintptr_t tag;
};


template <class T>
struct Node
{
    T data;
    pointer_t<Node<T> > next;
};

现在我想将pointer_t<Node<T> > newNext传递给__sync_bool_compare_and_swap()函数。根据我传递的函数的原型:

__sync_bool_compare_and_swap((unsigned long*) &newTail.ptr->next, oldNext, newNext)

问题是,如果我不将newNext投射到unsigned long,我会得到:

error: ‘struct pointer_t<Node<int> >’ used where a ‘long unsigned int’ was expected
      if ( __sync_bool_compare_and_swap((unsigned long*) &newTail.ptr->next, newNext, newNext) )

如果我将它转换为无符号长,那么:

if ( __sync_bool_compare_and_swap((unsigned long*) &newTail.ptr->next, (unsigned long) oldNext, (unsigned long) newNext) )

我会得到:

error: ‘struct pointer_t<Node<int> >’ used where a ‘long unsigned int’ was expected.

有人可以解释一下我可以将__sync_bool_compare_and_swap用于这两种结构吗?

感谢

2 个答案:

答案 0 :(得分:1)

#include <iostream>
#include <bitset>
using namespace std;

template <class T>
struct pointer_t
{
    T *ptr;
    uintptr_t tag;
};


template <class T>
struct Node
{
    T data;
    pointer_t<Node<T> >* next;
};

int main()
{
    Node<int> *newTail = new Node<int>();
    pointer_t<Node<int> > *oldNext = newTail->next;


    Node<int> *newNext = new Node<int>();

    pointer_t<Node<int> >* newNextPtr = new pointer_t<Node<int> >();
    newNextPtr->ptr=newNext;

    if ( __sync_bool_compare_and_swap(&newTail->next, oldNext, newNextPtr)) {
        std::cout<<"Gotcha!\n";
      }
 }

这并没有真正解决您的指针标记问题。如果你想要实现指针标记,只需从指针中窃取一些未使用的位并设置这些位以标记指针,然后取消设置它们以重置指针。在解除引用之前不要忘记解开这些位。

#define get_markedness(p) (((ptr_int) (p)) & 3)
#define get_unmarked_reference(p) ((void *) (((ptr_int) (p)) & (~3)))
#define get_marked_reference(p,m) ((void *) (((ptr_int) (p)) | m))

答案 1 :(得分:1)