| 1 | // SPDX-FileCopyrightText: 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
| 2 | // |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | |
| 5 | /* |
| 6 | * This example shows how to remove from a linked-list safely against |
| 7 | * concurrent RCU traversals. |
| 8 | */ |
| 9 | |
| 10 | #include <stdio.h> |
| 11 | |
| 12 | #include <urcu/urcu-memb.h> /* Userspace RCU flavor */ |
| 13 | #include <urcu/rculist.h> /* RCU list */ |
| 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_list_head node; /* Linked-list chaining */ |
| 22 | struct rcu_head rcu_head; /* For call_rcu() */ |
| 23 | }; |
| 24 | |
| 25 | static |
| 26 | void 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 | |
| 33 | int main(void) |
| 34 | { |
| 35 | int values[] = { -5, 42, 36, 24, }; |
| 36 | CDS_LIST_HEAD(mylist); /* Defines an empty list 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_list_add_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_list_for_each_entry_safe(node, n, &mylist, node) { |
| 62 | if (node->value > 0) { |
| 63 | cds_list_del_rcu(&node->node); |
| 64 | /* |
| 65 | * We can only reclaim memory after a grace |
| 66 | * period has passed after cds_list_del_rcu(). |
| 67 | */ |
| 68 | urcu_memb_call_rcu(&node->rcu_head, free_node_rcu); |
| 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_list_for_each_entry(node, &mylist, node) { |
| 78 | printf(" %d", node->value); |
| 79 | } |
| 80 | printf("\n"); |
| 81 | end: |
| 82 | return ret; |
| 83 | } |