1 /*
2  * Copyright © 2019 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include "util/sparse_array.h"
25 
26 #include "c11/threads.h"
27 
28 #include <gtest/gtest.h>
29 
30 #define NUM_SETS_PER_THREAD (1 << 10)
31 #define MAX_ARR_SIZE (1 << 20)
32 
33 static int
test_thread(void * _state)34 test_thread(void *_state)
35 {
36    struct util_sparse_array *arr = (struct util_sparse_array *)_state;
37    for (unsigned i = 0; i < NUM_SETS_PER_THREAD; i++) {
38       uint32_t idx = rand() % MAX_ARR_SIZE;
39       uint32_t *elem = (uint32_t *)util_sparse_array_get(arr, idx);
40       *elem = idx;
41    }
42 
43    return 0;
44 }
45 
TEST(SparseArrayTest,Multithread)46 TEST(SparseArrayTest, Multithread)
47 {
48    const int num_runs = 16;
49 
50    for (unsigned run_idx = 0; run_idx < num_runs; run_idx++) {
51       size_t node_size = 4 << (run_idx / 2);
52 
53       struct util_sparse_array arr;
54       util_sparse_array_init(&arr, sizeof(uint32_t), node_size);
55 
56       thrd_t threads[16];
57       for (unsigned i = 0; i < ARRAY_SIZE(threads); i++) {
58          int ret = thrd_create(&threads[i], test_thread, &arr);
59          ASSERT_EQ(ret, thrd_success);
60       }
61 
62       for (unsigned i = 0; i < ARRAY_SIZE(threads); i++) {
63          int ret = thrd_join(threads[i], NULL);
64          ASSERT_EQ(ret, thrd_success);
65       }
66 
67       util_sparse_array_validate(&arr);
68 
69       for (unsigned i = 0; i < MAX_ARR_SIZE; i++) {
70          uint32_t *elem = (uint32_t *)util_sparse_array_get(&arr, i);
71          ASSERT_TRUE(*elem == 0 || *elem == i)
72             << "Element at index " << i << " is " << *elem
73             << " but expected zero or " << i;
74       }
75 
76       util_sparse_array_finish(&arr);
77    }
78 }
79