Commit | Line | Data |
---|---|---|
d4b71408 MD |
1 | /* |
2 | * Copyright (C) 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> | |
3 | * | |
4 | * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED | |
5 | * OR IMPLIED. ANY USE IS AT YOUR OWN RISK. | |
6 | * | |
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. | |
12 | * | |
13 | * This example shows how to enqueue nodes into a RCU lock-free queue. | |
14 | * This queue requires using a RCU scheme. | |
15 | */ | |
16 | ||
17 | #include <stdio.h> | |
18 | #include <stdlib.h> | |
19 | ||
b9050d91 | 20 | #include <urcu/urcu-memb.h> /* RCU flavor */ |
d4b71408 MD |
21 | #include <urcu/rculfqueue.h> /* RCU Lock-free queue */ |
22 | #include <urcu/compiler.h> /* For CAA_ARRAY_SIZE */ | |
23 | ||
24 | /* | |
25 | * Nodes populated into the queue. | |
26 | */ | |
27 | struct mynode { | |
28 | int value; /* Node content */ | |
29 | struct cds_lfq_node_rcu node; /* Chaining in queue */ | |
30 | }; | |
31 | ||
32 | int main(int argc, char **argv) | |
33 | { | |
34 | int values[] = { -5, 42, 36, 24, }; | |
35 | struct cds_lfq_queue_rcu myqueue; /* Queue */ | |
36 | unsigned int i; | |
37 | int ret = 0; | |
38 | ||
39 | /* | |
40 | * Each thread need using RCU read-side need to be explicitly | |
41 | * registered. | |
42 | */ | |
b9050d91 | 43 | urcu_memb_register_thread(); |
d4b71408 | 44 | |
b9050d91 | 45 | cds_lfq_init_rcu(&myqueue, urcu_memb_call_rcu); |
d4b71408 MD |
46 | |
47 | /* | |
48 | * Enqueue nodes. | |
49 | */ | |
50 | for (i = 0; i < CAA_ARRAY_SIZE(values); i++) { | |
51 | struct mynode *node; | |
52 | ||
53 | node = malloc(sizeof(*node)); | |
54 | if (!node) { | |
55 | ret = -1; | |
56 | goto end; | |
57 | } | |
58 | ||
59 | cds_lfq_node_init_rcu(&node->node); | |
60 | node->value = values[i]; | |
61 | /* | |
62 | * Both enqueue and dequeue need to be called within RCU | |
63 | * read-side critical section. | |
64 | */ | |
b9050d91 | 65 | urcu_memb_read_lock(); |
d4b71408 | 66 | cds_lfq_enqueue_rcu(&myqueue, &node->node); |
b9050d91 | 67 | urcu_memb_read_unlock(); |
d4b71408 MD |
68 | } |
69 | ||
70 | end: | |
b9050d91 | 71 | urcu_memb_unregister_thread(); |
d4b71408 MD |
72 | return ret; |
73 | } |