Commit | Line | Data |
---|---|---|
1c87adb3 MJ |
1 | // SPDX-FileCopyrightText: 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
2 | // | |
3 | // SPDX-License-Identifier: MIT | |
4 | ||
d4b71408 | 5 | /* |
d4b71408 MD |
6 | * This example shows how to enqueue nodes into a RCU lock-free queue. |
7 | * This queue requires using a RCU scheme. | |
8 | */ | |
9 | ||
10 | #include <stdio.h> | |
11 | #include <stdlib.h> | |
12 | ||
b9050d91 | 13 | #include <urcu/urcu-memb.h> /* RCU flavor */ |
d4b71408 MD |
14 | #include <urcu/rculfqueue.h> /* RCU Lock-free queue */ |
15 | #include <urcu/compiler.h> /* For CAA_ARRAY_SIZE */ | |
16 | ||
17 | /* | |
18 | * Nodes populated into the queue. | |
19 | */ | |
20 | struct mynode { | |
21 | int value; /* Node content */ | |
22 | struct cds_lfq_node_rcu node; /* Chaining in queue */ | |
23 | }; | |
24 | ||
70469b43 | 25 | int main(void) |
d4b71408 MD |
26 | { |
27 | int values[] = { -5, 42, 36, 24, }; | |
28 | struct cds_lfq_queue_rcu myqueue; /* Queue */ | |
29 | unsigned int i; | |
30 | int ret = 0; | |
31 | ||
32 | /* | |
33 | * Each thread need using RCU read-side need to be explicitly | |
34 | * registered. | |
35 | */ | |
b9050d91 | 36 | urcu_memb_register_thread(); |
d4b71408 | 37 | |
b9050d91 | 38 | cds_lfq_init_rcu(&myqueue, urcu_memb_call_rcu); |
d4b71408 MD |
39 | |
40 | /* | |
41 | * Enqueue nodes. | |
42 | */ | |
43 | for (i = 0; i < CAA_ARRAY_SIZE(values); i++) { | |
44 | struct mynode *node; | |
45 | ||
46 | node = malloc(sizeof(*node)); | |
47 | if (!node) { | |
48 | ret = -1; | |
49 | goto end; | |
50 | } | |
51 | ||
52 | cds_lfq_node_init_rcu(&node->node); | |
53 | node->value = values[i]; | |
54 | /* | |
55 | * Both enqueue and dequeue need to be called within RCU | |
56 | * read-side critical section. | |
57 | */ | |
b9050d91 | 58 | urcu_memb_read_lock(); |
d4b71408 | 59 | cds_lfq_enqueue_rcu(&myqueue, &node->node); |
b9050d91 | 60 | urcu_memb_read_unlock(); |
d4b71408 MD |
61 | } |
62 | ||
63 | end: | |
b9050d91 | 64 | urcu_memb_unregister_thread(); |
d4b71408 MD |
65 | return ret; |
66 | } |