| 1 | /* |
| 2 | * Copyright (C) 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
| 3 | * |
| 4 | * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED |
| 5 | * OR IMPLIED. ANY USE IS AT YOUR OWN RISK. |
| 6 | * |
| 7 | * Permission is hereby granted to use or copy this program for any |
| 8 | * purpose, provided the above notices are retained on all copies. |
| 9 | * Permission to modify the code and to distribute modified code is |
| 10 | * granted, provided the above notices are retained, and a notice that |
| 11 | * the code was modified is included with the above copyright notice. |
| 12 | * |
| 13 | * This example shows how to do a RCU linked list traversal, safely |
| 14 | * against concurrent RCU updates. |
| 15 | */ |
| 16 | |
| 17 | #include <stdio.h> |
| 18 | |
| 19 | #include <urcu/urcu-memb.h> /* Userspace RCU flavor */ |
| 20 | #include <urcu/rculist.h> /* RCU list */ |
| 21 | #include <urcu/compiler.h> /* For CAA_ARRAY_SIZE */ |
| 22 | |
| 23 | /* |
| 24 | * Nodes populated into the list. |
| 25 | */ |
| 26 | struct mynode { |
| 27 | int value; /* Node content */ |
| 28 | struct cds_list_head node; /* Linked-list chaining */ |
| 29 | }; |
| 30 | |
| 31 | int main(void) |
| 32 | { |
| 33 | int values[] = { -5, 42, 36, 24, }; |
| 34 | CDS_LIST_HEAD(mylist); /* Defines an empty list head */ |
| 35 | unsigned int i; |
| 36 | int ret = 0; |
| 37 | struct mynode *node; |
| 38 | |
| 39 | /* |
| 40 | * Each thread need using RCU read-side need to be explicitly |
| 41 | * registered. |
| 42 | */ |
| 43 | urcu_memb_register_thread(); |
| 44 | |
| 45 | /* |
| 46 | * Adding nodes to the linked-list. Safe against concurrent |
| 47 | * RCU traversals, require mutual exclusion with list updates. |
| 48 | */ |
| 49 | for (i = 0; i < CAA_ARRAY_SIZE(values); i++) { |
| 50 | node = malloc(sizeof(*node)); |
| 51 | if (!node) { |
| 52 | ret = -1; |
| 53 | goto end; |
| 54 | } |
| 55 | node->value = values[i]; |
| 56 | cds_list_add_tail_rcu(&node->node, &mylist); |
| 57 | } |
| 58 | |
| 59 | /* |
| 60 | * RCU-safe iteration on the list. |
| 61 | */ |
| 62 | printf("mylist content:"); |
| 63 | |
| 64 | /* |
| 65 | * Surround the RCU read-side critical section with urcu_memb_read_lock() |
| 66 | * and urcu_memb_read_unlock(). |
| 67 | */ |
| 68 | urcu_memb_read_lock(); |
| 69 | |
| 70 | /* |
| 71 | * This traversal can be performed concurrently with RCU |
| 72 | * updates. |
| 73 | */ |
| 74 | cds_list_for_each_entry_rcu(node, &mylist, node) { |
| 75 | printf(" %d", node->value); |
| 76 | } |
| 77 | |
| 78 | urcu_memb_read_unlock(); |
| 79 | |
| 80 | printf("\n"); |
| 81 | end: |
| 82 | urcu_memb_unregister_thread(); |
| 83 | return ret; |
| 84 | } |