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