doc: update examples to API changes
[urcu.git] / doc / examples / hlist / cds_hlist_for_each_rcu.c
CommitLineData
474190bf
MD
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 non-circular RCU linked list
14 * traversal, safely against concurrent RCU updates.
15 * cds_hlist_for_each_rcu() iterates on struct cds_hlist_node, and thus,
16 * either caa_container_of() or cds_hlist_entry() are needed to access
17 * the container structure.
18 */
19
20#include <stdio.h>
21
b9050d91 22#include <urcu/urcu-memb.h> /* Userspace RCU flavor */
474190bf
MD
23#include <urcu/rcuhlist.h> /* RCU hlist */
24#include <urcu/compiler.h> /* For CAA_ARRAY_SIZE */
25
26/*
27 * Nodes populated into the list.
28 */
29struct mynode {
30 int value; /* Node content */
31 struct cds_hlist_node node; /* Linked-list chaining */
32};
33
34int main(int argc, char **argv)
35{
36 int values[] = { -5, 42, 36, 24, };
37 CDS_HLIST_HEAD(mylist); /* Defines an empty hlist head */
38 unsigned int i;
39 int ret = 0;
40 struct cds_hlist_node *pos;
41
42 /*
43 * Each thread need using RCU read-side need to be explicitly
44 * registered.
45 */
b9050d91 46 urcu_memb_register_thread();
474190bf
MD
47
48 /*
49 * Adding nodes to the linked-list. Safe against concurrent
50 * RCU traversals, require mutual exclusion with list updates.
51 */
52 for (i = 0; i < CAA_ARRAY_SIZE(values); i++) {
53 struct mynode *node;
54
55 node = malloc(sizeof(*node));
56 if (!node) {
57 ret = -1;
58 goto end;
59 }
60 node->value = values[i];
61 cds_hlist_add_head_rcu(&node->node, &mylist);
62 }
63
64 /*
65 * RCU-safe iteration on the list.
66 */
67 printf("mylist content:");
68
69 /*
70 * Surround the RCU read-side critical section with rcu_read_lock()
71 * and rcu_read_unlock().
72 */
b9050d91 73 urcu_memb_read_lock();
474190bf
MD
74
75 /*
76 * This traversal can be performed concurrently with RCU
77 * updates.
78 */
79 cds_hlist_for_each_rcu(pos, &mylist) {
80 struct mynode *node = cds_hlist_entry(pos, struct mynode, node);
81
82 printf(" %d", node->value);
83 }
84
b9050d91 85 urcu_memb_read_unlock();
474190bf
MD
86
87 printf("\n");
88end:
b9050d91 89 urcu_memb_unregister_thread();
474190bf
MD
90 return ret;
91}
This page took 0.031965 seconds and 4 git commands to generate.