Commit | Line | Data |
---|---|---|
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 | */ | |
9 | ||
10 | #include <stdio.h> | |
11 | ||
b9050d91 | 12 | #include <urcu/urcu-memb.h> /* Userspace RCU flavor */ |
474190bf MD |
13 | #include <urcu/rcuhlist.h> /* RCU hlist */ |
14 | #include <urcu/compiler.h> /* For CAA_ARRAY_SIZE */ | |
15 | ||
16 | /* | |
17 | * Nodes populated into the list. | |
18 | */ | |
19 | struct mynode { | |
20 | int value; /* Node content */ | |
21 | struct cds_hlist_node node; /* Linked-list chaining */ | |
22 | }; | |
23 | ||
70469b43 | 24 | int main(void) |
474190bf MD |
25 | { |
26 | int values[] = { -5, 42, 36, 24, }; | |
27 | CDS_HLIST_HEAD(mylist); /* Defines an empty hlist head */ | |
28 | unsigned int i; | |
29 | int ret = 0; | |
30 | struct mynode *node; | |
31 | ||
32 | /* | |
33 | * Each thread need using RCU read-side need to be explicitly | |
34 | * registered. | |
35 | */ | |
b9050d91 | 36 | urcu_memb_register_thread(); |
474190bf MD |
37 | |
38 | /* | |
39 | * Adding nodes to the linked-list. Safe against concurrent | |
40 | * RCU traversals, require mutual exclusion with list updates. | |
41 | */ | |
42 | for (i = 0; i < CAA_ARRAY_SIZE(values); i++) { | |
43 | node = malloc(sizeof(*node)); | |
44 | if (!node) { | |
45 | ret = -1; | |
46 | goto end; | |
47 | } | |
48 | node->value = values[i]; | |
49 | cds_hlist_add_head_rcu(&node->node, &mylist); | |
50 | } | |
51 | ||
52 | /* | |
53 | * RCU-safe iteration on the list. | |
54 | */ | |
55 | printf("mylist content:"); | |
56 | ||
57 | /* | |
58 | * Surround the RCU read-side critical section with rcu_read_lock() | |
59 | * and rcu_read_unlock(). | |
60 | */ | |
b9050d91 | 61 | urcu_memb_read_lock(); |
474190bf MD |
62 | |
63 | /* | |
64 | * This traversal can be performed concurrently with RCU | |
65 | * updates. | |
66 | */ | |
67 | cds_hlist_for_each_entry_rcu_2(node, &mylist, node) { | |
68 | printf(" %d", node->value); | |
69 | } | |
70 | ||
b9050d91 | 71 | urcu_memb_read_unlock(); |
474190bf MD |
72 | |
73 | printf("\n"); | |
74 | end: | |
b9050d91 | 75 | urcu_memb_unregister_thread(); |
474190bf MD |
76 | return ret; |
77 | } |