| 1 | // SPDX-FileCopyrightText: 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
| 2 | // |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | |
| 5 | /* |
| 6 | * This example shows how to add into 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 | }; |
| 23 | |
| 24 | int main(void) |
| 25 | { |
| 26 | int values[] = { -5, 42, 36, 24, }; |
| 27 | CDS_LIST_HEAD(mylist); /* Defines an empty list head */ |
| 28 | unsigned int i; |
| 29 | int ret = 0; |
| 30 | struct mynode *node; |
| 31 | |
| 32 | /* |
| 33 | * Adding nodes to the linked-list. Safe against concurrent |
| 34 | * RCU traversals, require mutual exclusion with list updates. |
| 35 | */ |
| 36 | for (i = 0; i < CAA_ARRAY_SIZE(values); i++) { |
| 37 | node = malloc(sizeof(*node)); |
| 38 | if (!node) { |
| 39 | ret = -1; |
| 40 | goto end; |
| 41 | } |
| 42 | node->value = values[i]; |
| 43 | cds_list_add_rcu(&node->node, &mylist); |
| 44 | } |
| 45 | |
| 46 | /* |
| 47 | * Just show the list content. This is _not_ an RCU-safe |
| 48 | * iteration on the list. |
| 49 | */ |
| 50 | printf("mylist content:"); |
| 51 | cds_list_for_each_entry(node, &mylist, node) { |
| 52 | printf(" %d", node->value); |
| 53 | } |
| 54 | printf("\n"); |
| 55 | end: |
| 56 | return ret; |
| 57 | } |