2 * Copyright (C) 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
4 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
5 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
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.
13 * This example shows how to add nodes (allowing duplicate keys) into a
14 * RCU lock-free hash table.
15 * This hash table requires using a RCU scheme.
22 #include <urcu/urcu-memb.h> /* RCU flavor */
23 #include <urcu/rculfhash.h> /* RCU Lock-free hash table */
24 #include <urcu/compiler.h> /* For CAA_ARRAY_SIZE */
25 #include "jhash.h" /* Example hash function */
28 * Nodes populated into the hash table.
31 int value
; /* Node content */
32 struct cds_lfht_node node
; /* Chaining in hash table */
37 int values
[] = { -5, 42, 42, 36, 24, }; /* 42 is duplicated */
38 struct cds_lfht
*ht
; /* Hash table */
42 struct cds_lfht_iter iter
; /* For iteration on hash table */
46 * Each thread need using RCU read-side need to be explicitly
49 urcu_memb_register_thread();
51 /* Use time as seed for hash table hashing. */
52 seed
= (uint32_t) time(NULL
);
55 * Allocate hash table.
57 ht
= cds_lfht_new_flavor(1, 1, 0,
58 CDS_LFHT_AUTO_RESIZE
| CDS_LFHT_ACCOUNTING
,
59 &urcu_memb_flavor
, NULL
);
61 printf("Error allocating hash table\n");
67 * Add nodes to hash table.
69 for (i
= 0; i
< CAA_ARRAY_SIZE(values
); i
++) {
72 node
= malloc(sizeof(*node
));
78 cds_lfht_node_init(&node
->node
);
79 node
->value
= values
[i
];
80 hash
= jhash(&values
[i
], sizeof(values
[i
]), seed
);
83 * cds_lfht_add() needs to be called from RCU read-side
86 urcu_memb_read_lock();
87 cds_lfht_add(ht
, hash
, &node
->node
);
88 urcu_memb_read_unlock();
92 * Iterate over each hash table node. Those will appear in
93 * random order, depending on the hash seed. Iteration needs to
94 * be performed within RCU read-side critical section.
96 printf("hash table content (random order):");
97 urcu_memb_read_lock();
98 cds_lfht_for_each_entry(ht
, &iter
, node
, node
) {
99 printf(" %d", node
->value
);
101 urcu_memb_read_unlock();
104 urcu_memb_unregister_thread();
This page took 0.041773 seconds and 4 git commands to generate.