File: utest-spinlock.cpp

package info (click to toggle)
python-pyclustering 0.10.1.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 11,128 kB
  • sloc: cpp: 38,888; python: 24,311; sh: 384; makefile: 105
file content (76 lines) | stat: -rwxr-xr-x 1,700 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*!

@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause

*/


#include <gtest/gtest.h>

#include <pyclustering/parallel/spinlock.hpp>
#include <pyclustering/parallel/thread_pool.hpp>

#include <algorithm>


using namespace pyclustering::parallel;


TEST(utest_spinlock, count_value) {
    const std::size_t amount_count = 100000;
    const std::size_t amount_tasks = 50;

    std::vector<std::thread> pool;

    std::size_t result = 0;
    spinlock locker;
    auto task = [&result, &locker, amount_count]() {
        for (std::size_t i = 0; i < amount_count; i++) {
            locker.lock();
            result++;
            locker.unlock();
        }
    };

    for (std::size_t i = 0; i < amount_tasks; i++) {
        pool.emplace_back(task);
    }

    for (std::size_t i = 0; i < amount_tasks; i++) {
        pool[i].join();
    }

    ASSERT_EQ(amount_count * amount_tasks, result);
}


TEST(utest_spinlock, count_value_thread_pool) {
    const std::size_t amount_threads = 20;
    const std::size_t amount_count = 1000;
    const std::size_t amount_tasks = 1000;

    thread_pool pool(amount_threads);

    std::size_t result = 0;
    spinlock locker;
    auto task = [&result, &locker, amount_count]() {
        for (std::size_t i = 0; i < amount_count; i++) {
            locker.lock();
            result++;
            locker.unlock();
        }
    };

    std::vector<task::ptr> tasks(amount_tasks);
    for (std::size_t i = 0; i < amount_tasks; i++) {
        tasks[i] = pool.add_task(task);
    }

    for (std::size_t i = 0; i < amount_tasks; i++) {
        tasks[i]->wait_ready();
    }

    ASSERT_EQ(amount_count * amount_tasks, result);
}