uatomic/x86: Remove redundant memory barriers
[urcu.git] / doc / examples / list / cds_list_for_each_rcu.c
1 // SPDX-FileCopyrightText: 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
2 //
3 // SPDX-License-Identifier: MIT
4
5 /*
6 * This example shows how to do a RCU linked list traversal, safely
7 * against concurrent RCU updates. cds_list_for_each_rcu() iterates on
8 * struct cds_list_head, and thus, either caa_container_of() or
9 * cds_list_entry() are needed to access the container structure.
10 */
11
12 #include <stdio.h>
13
14 #include <urcu/urcu-memb.h> /* Userspace RCU flavor */
15 #include <urcu/rculist.h> /* RCU list */
16 #include <urcu/compiler.h> /* For CAA_ARRAY_SIZE */
17
18 /*
19 * Nodes populated into the list.
20 */
21 struct mynode {
22 int value; /* Node content */
23 struct cds_list_head node; /* Linked-list chaining */
24 };
25
26 int main(void)
27 {
28 int values[] = { -5, 42, 36, 24, };
29 CDS_LIST_HEAD(mylist); /* Defines an empty list head */
30 unsigned int i;
31 int ret = 0;
32 struct cds_list_head *pos;
33
34 /*
35 * Each thread need using RCU read-side need to be explicitly
36 * registered.
37 */
38 urcu_memb_register_thread();
39
40 /*
41 * Adding nodes to the linked-list. Safe against concurrent
42 * RCU traversals, require mutual exclusion with list updates.
43 */
44 for (i = 0; i < CAA_ARRAY_SIZE(values); i++) {
45 struct mynode *node;
46
47 node = malloc(sizeof(*node));
48 if (!node) {
49 ret = -1;
50 goto end;
51 }
52 node->value = values[i];
53 cds_list_add_tail_rcu(&node->node, &mylist);
54 }
55
56 /*
57 * RCU-safe iteration on the list.
58 */
59 printf("mylist content:");
60
61 /*
62 * Surround the RCU read-side critical section with urcu_memb_read_lock()
63 * and urcu_memb_read_unlock().
64 */
65 urcu_memb_read_lock();
66
67 /*
68 * This traversal can be performed concurrently with RCU
69 * updates.
70 */
71 cds_list_for_each_rcu(pos, &mylist) {
72 struct mynode *node = cds_list_entry(pos, struct mynode, node);
73
74 printf(" %d", node->value);
75 }
76
77 urcu_memb_read_unlock();
78
79 printf("\n");
80 end:
81 urcu_memb_unregister_thread();
82 return ret;
83 }
This page took 0.030861 seconds and 5 git commands to generate.