【发布时间】:2016-07-11 23:01:15
【问题描述】:
尝试我的运气来实现无锁单链表。
typedef _Atomic struct _node
{
void *data;
struct _node *next;
} Node;
这是否使 _Atomic 结构的所有成员也都是原子的?
void add_head ( Linked_list* list, void* data )
{
if ( debugging )
{
printf ( "%s\n", __func__ );
}
Node *node = ( Node* ) calloc ( 1, sizeof (Node ) );
//init_node_mutex(node);
//lock_node_mutex(node);
atomic_exchange ( &node->next, NULL );
atomic_exchange ( &node->data, data );
if ( list->head == NULL )
{
Node* the_tail = atomic_load ( &list->tail );
// lock_node_mutex ( the_tail );
atomic_exchange ( &node->next, NULL );
atomic_compare_exchange_weak ( &list->tail, the_tail, node );
//unlock_node_mutex ( the_tail );
}
else
{
Node* the_next = atomic_load ( &node->next );
// lock_node_mutex ( the_next );
atomic_compare_exchange_weak ( &node->next, the_next, list->head );
// unlock_node_mutex ( the_next );
}
Node* the_head = atomic_load ( & list->head );
//lock_node_mutex ( the_head );
atomic_store ( &list->head, node );
atomic_store ( &list->current, node );
//unlock_node_mutex ( the_head );
//unlock_node_mutex(node);
atomic_fetch_add ( &list->size, 1 );
}
atomic_load 和 atomic_store 的用法是否正确?
【问题讨论】:
-
在 C11 标准中,第 §6.5.2.3 节 结构和联合成员(对于
.和->运算符)¶5 说 访问成员对原子结构或联合对象的访问会导致未定义的行为。97) 并且脚注 97 说 例如,如果在一个线程中访问整个结构或联合与访问成员发生冲突,则会发生数据竞争从另一个线程,其中至少一个访问是修改。可以使用分配给原子对象或从原子对象分配的非原子对象安全地访问成员。