uatomic/x86: Remove redundant memory barriers
[urcu.git] / doc / examples / list / cds_list_replace_rcu.c
CommitLineData
1c87adb3
MJ
1// SPDX-FileCopyrightText: 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
2//
3// SPDX-License-Identifier: MIT
4
7eba9f88 5/*
7eba9f88
MD
6 * This example shows how to replace a node within a linked-list safely
7 * against concurrent RCU traversals.
8 */
9
10#include <stdio.h>
11
b9050d91 12#include <urcu/urcu-memb.h> /* Userspace RCU flavor */
7eba9f88
MD
13#include <urcu/rculist.h> /* RCU list */
14#include <urcu/compiler.h> /* For CAA_ARRAY_SIZE */
15
16/*
17 * Nodes populated into the list.
18 */
19struct mynode {
20 int value; /* Node content */
21 struct cds_list_head node; /* Linked-list chaining */
22 struct rcu_head rcu_head; /* For call_rcu() */
23};
24
25static
26void free_node_rcu(struct rcu_head *head)
27{
28 struct mynode *node = caa_container_of(head, struct mynode, rcu_head);
29
30 free(node);
31}
32
70469b43 33int main(void)
7eba9f88
MD
34{
35 int values[] = { -5, 42, 36, 24, };
36 CDS_LIST_HEAD(mylist); /* Defines an empty list head */
37 unsigned int i;
38 int ret = 0;
39 struct mynode *node, *n;
40
41 /*
42 * Adding nodes to the linked-list. Safe against concurrent
43 * RCU traversals, require mutual exclusion with list updates.
44 */
45 for (i = 0; i < CAA_ARRAY_SIZE(values); i++) {
46 node = malloc(sizeof(*node));
47 if (!node) {
48 ret = -1;
49 goto end;
50 }
51 node->value = values[i];
52 cds_list_add_tail_rcu(&node->node, &mylist);
53 }
54
55 /*
56 * Replacing all values by their negated value. Safe against
57 * concurrent RCU traversals, require mutual exclusion with list
58 * updates. Notice the "safe" iteration: it is safe against
59 * removal (and thus replacement) of nodes as we iterate on the
60 * list.
61 */
62 cds_list_for_each_entry_safe(node, n, &mylist, node) {
63 struct mynode *new_node;
64
65 new_node = malloc(sizeof(*node));
66 if (!new_node) {
67 ret = -1;
68 goto end;
69 }
70 /* Replacement node value is negated original value. */
71 new_node->value = -node->value;
72 cds_list_replace_rcu(&node->node, &new_node->node);
b9050d91 73 urcu_memb_call_rcu(&node->rcu_head, free_node_rcu);
7eba9f88
MD
74 }
75
76 /*
77 * Just show the list content. This is _not_ an RCU-safe
78 * iteration on the list.
79 */
80 printf("mylist content:");
81 cds_list_for_each_entry(node, &mylist, node) {
82 printf(" %d", node->value);
83 }
84 printf("\n");
85end:
86 return ret;
87}
This page took 0.038963 seconds and 4 git commands to generate.