| 1 | // SPDX-FileCopyrightText: 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
| 2 | // |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | |
| 5 | /* |
| 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 | |
| 13 | #include <urcu/urcu-memb.h> /* RCU flavor */ |
| 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 | |
| 25 | int main(void) |
| 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 | */ |
| 36 | urcu_memb_register_thread(); |
| 37 | |
| 38 | cds_lfq_init_rcu(&myqueue, urcu_memb_call_rcu); |
| 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 | */ |
| 58 | urcu_memb_read_lock(); |
| 59 | cds_lfq_enqueue_rcu(&myqueue, &node->node); |
| 60 | urcu_memb_read_unlock(); |
| 61 | } |
| 62 | |
| 63 | end: |
| 64 | urcu_memb_unregister_thread(); |
| 65 | return ret; |
| 66 | } |