问题
I am trying to implement a lock free list. For this project I need and atomic compare and swap instruction that can compare a 32 bit pointer to my 'node' struct.
The node struct is as follows:
typedef struct node
{
int data;
struct node * next;
struct node * backlink;
}node_lf;
I am using _sync_val_compare_and_swap() to perform compare and swap operation. My question is, can this function return a value other than int? This is what I am trying to do:
node_lf cs(node_lf * address, cs_arg *old_val, cs_arg *new_val)
{
node_lf ptr;
ptr = (node_lf)__sync_val_compare_and_swap ((int *)address, old_val->node, new_val->node);
return (ptr);
}
where cs_arg is another struct to hold the node pointer and other bookkeeping information.
If there are any other methods to implement atomic compare and swap, please suggest.
回答1:
My question is, can this function return a value other than int?
The answer is yes, __sync_val_compare_and_swap
can work with types other than int
, including char
, short
, long long
and __int128
(on x64).
Note that you may need to cast non-integer types to an appropriately-sized integer for __sync_val_compare_and_swap
to work with them.
来源:https://stackoverflow.com/questions/37743658/can-sync-val-compare-and-swap-return-anything-other-than-int