1 // SPDX-FileCopyrightText: 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
3 // SPDX-License-Identifier: MIT
6 * This example shows how to use cds_lfht_destroy() to clear memory used
7 * by a a RCU lock-free hash table. This hash table requires using a
15 #include <urcu/urcu-memb.h> /* RCU flavor */
16 #include <urcu/rculfhash.h> /* RCU Lock-free hash table */
17 #include <urcu/compiler.h> /* For CAA_ARRAY_SIZE */
18 #include "jhash.h" /* Example hash function */
21 * Nodes populated into the hash table.
24 int value
; /* Node content */
25 struct cds_lfht_node node
; /* Chaining in hash table */
26 struct rcu_head rcu_head
; /* For call_rcu() */
30 void free_node(struct rcu_head
*head
)
32 struct mynode
*node
= caa_container_of(head
, struct mynode
, rcu_head
);
39 int values
[] = { -5, 42, 42, 36, 24, }; /* 42 is duplicated */
40 struct cds_lfht
*ht
; /* Hash table */
44 struct cds_lfht_iter iter
; /* For iteration on hash table */
45 struct cds_lfht_node
*ht_node
;
49 * Each thread need using RCU read-side need to be explicitly
52 urcu_memb_register_thread();
54 /* Use time as seed for hash table hashing. */
55 seed
= (uint32_t) time(NULL
);
58 * Allocate hash table.
60 ht
= cds_lfht_new_flavor(1, 1, 0,
61 CDS_LFHT_AUTO_RESIZE
| CDS_LFHT_ACCOUNTING
,
62 &urcu_memb_flavor
, NULL
);
64 printf("Error allocating hash table\n");
70 * Add nodes to hash table.
72 for (i
= 0; i
< CAA_ARRAY_SIZE(values
); i
++) {
76 node
= malloc(sizeof(*node
));
82 cds_lfht_node_init(&node
->node
);
85 hash
= jhash(&value
, sizeof(value
), seed
);
88 * cds_lfht_add() needs to be called from RCU read-side
91 urcu_memb_read_lock();
92 cds_lfht_add(ht
, hash
, &node
->node
);
93 urcu_memb_read_unlock();
97 * Iterate over each hash table node. Those will appear in
98 * random order, depending on the hash seed. Iteration needs to
99 * be performed within RCU read-side critical section.
101 printf("hash table content (random order):");
102 urcu_memb_read_lock();
103 cds_lfht_for_each_entry(ht
, &iter
, node
, node
) {
104 printf(" %d", node
->value
);
106 urcu_memb_read_unlock();
111 * Make sure all hash table nodes are removed before destroying.
113 printf("removing all nodes:");
114 urcu_memb_read_lock();
115 cds_lfht_for_each_entry(ht
, &iter
, node
, node
) {
116 ht_node
= cds_lfht_iter_get_node(&iter
);
117 ret
= cds_lfht_del(ht
, ht_node
);
118 printf(" %d", node
->value
);
120 printf(" (concurrently deleted)");
122 urcu_memb_call_rcu(&node
->rcu_head
, free_node
);
125 urcu_memb_read_unlock();
129 * cds_lfht_destroy() must be called from a very specific
130 * context: it needs to be called from a registered RCU reader
131 * thread. However, this thread should _not_ be within a RCU
132 * read-side critical section. Also, it should _not_ be called
133 * from a call_rcu thread.
135 ret
= cds_lfht_destroy(ht
, NULL
);
137 printf("Destroying hash table failed\n");
140 urcu_memb_unregister_thread();
This page took 0.097175 seconds and 5 git commands to generate.