uatomic/x86: Remove redundant memory barriers
[urcu.git] / doc / examples / rculfhash / cds_lfht_add.c
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 nodes (allowing duplicate keys) into a
7 * RCU lock-free hash table.
8 * This hash table requires using a RCU scheme.
9 */
10
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <time.h>
14
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 */
19
20 /*
21 * Nodes populated into the hash table.
22 */
23 struct mynode {
24 int value; /* Node content */
25 struct cds_lfht_node node; /* Chaining in hash table */
26 };
27
28 int main(void)
29 {
30 int values[] = { -5, 42, 42, 36, 24, }; /* 42 is duplicated */
31 struct cds_lfht *ht; /* Hash table */
32 unsigned int i;
33 int ret = 0;
34 uint32_t seed;
35 struct cds_lfht_iter iter; /* For iteration on hash table */
36 struct mynode *node;
37
38 /*
39 * Each thread need using RCU read-side need to be explicitly
40 * registered.
41 */
42 urcu_memb_register_thread();
43
44 /* Use time as seed for hash table hashing. */
45 seed = (uint32_t) time(NULL);
46
47 /*
48 * Allocate hash table.
49 */
50 ht = cds_lfht_new_flavor(1, 1, 0,
51 CDS_LFHT_AUTO_RESIZE | CDS_LFHT_ACCOUNTING,
52 &urcu_memb_flavor, NULL);
53 if (!ht) {
54 printf("Error allocating hash table\n");
55 ret = -1;
56 goto end;
57 }
58
59 /*
60 * Add nodes to hash table.
61 */
62 for (i = 0; i < CAA_ARRAY_SIZE(values); i++) {
63 unsigned long hash;
64
65 node = malloc(sizeof(*node));
66 if (!node) {
67 ret = -1;
68 goto end;
69 }
70
71 cds_lfht_node_init(&node->node);
72 node->value = values[i];
73 hash = jhash(&values[i], sizeof(values[i]), seed);
74
75 /*
76 * cds_lfht_add() needs to be called from RCU read-side
77 * critical section.
78 */
79 urcu_memb_read_lock();
80 cds_lfht_add(ht, hash, &node->node);
81 urcu_memb_read_unlock();
82 }
83
84 /*
85 * Iterate over each hash table node. Those will appear in
86 * random order, depending on the hash seed. Iteration needs to
87 * be performed within RCU read-side critical section.
88 */
89 printf("hash table content (random order):");
90 urcu_memb_read_lock();
91 cds_lfht_for_each_entry(ht, &iter, node, node) {
92 printf(" %d", node->value);
93 }
94 urcu_memb_read_unlock();
95 printf("\n");
96 end:
97 urcu_memb_unregister_thread();
98 return ret;
99 }
This page took 0.032162 seconds and 5 git commands to generate.