uatomic/x86: Remove redundant memory barriers
[urcu.git] / doc / examples / hlist / cds_hlist_del_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 remove from a non-circular linked-list
7 * safely against concurrent RCU traversals.
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 */
19struct mynode {
20 int value; /* Node content */
21 struct cds_hlist_node 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)
474190bf
MD
34{
35 int values[] = { -5, 42, 36, 24, };
36 CDS_HLIST_HEAD(mylist); /* Defines an empty hlist 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_hlist_add_head_rcu(&node->node, &mylist);
53 }
54
55 /*
56 * Removing all positive values. Safe against concurrent RCU
57 * traversals, require mutual exclusion with list updates.
58 * Notice the "safe" iteration: it is safe against removal of
59 * nodes as we iterate on the list.
60 */
61 cds_hlist_for_each_entry_safe_2(node, n, &mylist, node) {
62 if (node->value > 0) {
63 cds_hlist_del_rcu(&node->node);
64 /*
65 * We can only reclaim memory after a grace
66 * period has passed after cds_hlist_del_rcu().
67 */
b9050d91 68 urcu_memb_call_rcu(&node->rcu_head, free_node_rcu);
474190bf
MD
69 }
70 }
71
72 /*
73 * Just show the list content. This is _not_ an RCU-safe
74 * iteration on the list.
75 */
76 printf("mylist content:");
77 cds_hlist_for_each_entry_2(node, &mylist, node) {
78 printf(" %d", node->value);
79 }
80 printf("\n");
81end:
82 return ret;
83}
This page took 0.038891 seconds and 4 git commands to generate.