uatomic/x86: Remove redundant memory barriers
[urcu.git] / doc / examples / list / cds_list_for_each_rcu.c
CommitLineData
1c87adb3
MJ
1// SPDX-FileCopyrightText: 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
2//
3// SPDX-License-Identifier: MIT
4
17fb3188 5/*
8fd9af4a 6 * This example shows how to do a RCU linked list traversal, safely
17fb3188
MD
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
b9050d91 14#include <urcu/urcu-memb.h> /* Userspace RCU flavor */
17fb3188
MD
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 */
21struct mynode {
22 int value; /* Node content */
23 struct cds_list_head node; /* Linked-list chaining */
24};
25
70469b43 26int main(void)
17fb3188
MD
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 /*
8fd9af4a 35 * Each thread need using RCU read-side need to be explicitly
17fb3188
MD
36 * registered.
37 */
b9050d91 38 urcu_memb_register_thread();
17fb3188
MD
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 /*
b9050d91
MD
62 * Surround the RCU read-side critical section with urcu_memb_read_lock()
63 * and urcu_memb_read_unlock().
17fb3188 64 */
b9050d91 65 urcu_memb_read_lock();
17fb3188
MD
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
b9050d91 77 urcu_memb_read_unlock();
17fb3188
MD
78
79 printf("\n");
80end:
b9050d91 81 urcu_memb_unregister_thread();
17fb3188
MD
82 return ret;
83}
This page took 0.039127 seconds and 4 git commands to generate.