File: test_semaphore.cpp

package info (click to toggle)
onetbb 2022.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 19,440 kB
  • sloc: cpp: 129,228; ansic: 9,745; python: 808; xml: 183; objc: 176; makefile: 66; sh: 66; awk: 41; javascript: 37
file content (298 lines) | stat: -rw-r--r-- 8,993 bytes parent folder | download | duplicates (6)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/*
    Copyright (c) 2005-2022 Intel Corporation

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

//! \file test_semaphore.cpp
//! \brief Test for [internal] functionality

#if _WIN32 || _WIN64
#define _CRT_SECURE_NO_WARNINGS
#endif

// Test for counting semaphore
#include "common/test.h"
#include "common/utils.h"
#include "common/spin_barrier.h"
#include "tbb/blocked_range.h"
#include "tbb/tick_count.h"
#include "../../src/tbb/semaphore.h"
#include <atomic>
#include <vector>

using tbb::detail::r1::semaphore;

std::atomic<int> pCount;
utils::SpinBarrier sBarrier;

// Semaphore basis function:
//  set semaphore to initial value
// see that semaphore only allows that number of threads to be active
class Body : utils::NoAssign {
    const int nIters;
    semaphore& mySem;
    std::vector<int>& ourCounts;
    std::vector<double>& tottime;

    static constexpr int tickCounts = 1; // millisecond
    static constexpr int innerWait = 5; // millisecond
public:
    Body( int nThread, int nIter, semaphore& sem,
          std::vector<int>& our_counts, std::vector<double>& tot_time )
        : nIters(nIter), mySem(sem), ourCounts(our_counts), tottime(tot_time)
    {
        sBarrier.initialize(nThread);
        pCount = 0;
    }

    void operator()( const int tid ) const {
        sBarrier.wait();

        for (int i = 0; i < nIters; ++i) {
            utils::Sleep(tid * tickCounts);
            tbb::tick_count t0 = tbb::tick_count::now();
            mySem.P();
            tbb::tick_count t1 = tbb::tick_count::now();
            tottime[tid] += (t1 - t0).seconds();

            int curval = ++pCount;
            if (curval > ourCounts[tid]) {
                ourCounts[tid] = curval;
            }
            utils::Sleep(innerWait);
            --pCount;
            REQUIRE(int(pCount) >= 0);
            mySem.V();
        }
    }
}; // class Body

void test_semaphore( int sem_init_cnt, int extra_threads ) {
    semaphore my_sem(sem_init_cnt);
    int n_threads = sem_init_cnt + extra_threads;

    std::vector<int> max_vals(n_threads);
    std::vector<double> tot_times(n_threads);

    int n_iters = 10;
    Body body(n_threads, n_iters, my_sem, max_vals, tot_times);

    pCount = 0;
    utils::NativeParallelFor(n_threads, body);
    REQUIRE_MESSAGE(!pCount, "not all threads decremented pCount");

    int max_count = -1;
    for (auto item : max_vals) {
        max_count = utils::max(max_count, item);
    }
    REQUIRE_MESSAGE(max_count <= sem_init_cnt, "Too many threads in semaphore-protected increment");
}

#include "../../src/tbb/semaphore.cpp"
#if _WIN32 || _WIN64
#include "../../src/tbb/dynamic_link.cpp"
#endif

constexpr std::size_t N_TIMES = 1000;

template <typename S>
struct Counter {
    std::atomic<long> value;
    S my_sem;
    Counter() : value(0) {}
}; // struct Counter

// Function object for use with parallel_for.h
template <typename C>
struct AddOne : utils::NoAssign {
    C& my_counter;

    // Increments counter once for each iteration in the iteration space
    void operator()( int ) const {
        for (std::size_t i = 0; i < N_TIMES; ++i) {
            my_counter.my_sem.P();
            ++my_counter.value;
            my_counter.my_sem.V();
        }
    }

    AddOne( C& c ) : my_counter(c) {
        my_counter.my_sem.V();
    }
}; // struct AddOne

void test_binary_semaphore( int n_threads ) {
    Counter<tbb::detail::r1::binary_semaphore> counter;
    AddOne<decltype(counter)> AddOneBody(counter);
    utils::NativeParallelFor(n_threads, AddOneBody);
    REQUIRE_MESSAGE(n_threads * N_TIMES == counter.value, "Binary semaphore operations P()/V() have a race");
}

// Power of 2, the most tokens that can be in flight
constexpr std::size_t MAX_TOKENS = 32;
enum FilterType { imaProducer, imaConsumer };

class FilterBase : utils::NoAssign {
protected:
    FilterType ima;
    unsigned totTokens; // total number of tokens to be emitted, only used by producer
    std::atomic<unsigned>& myTokens;
    std::atomic<unsigned>& otherTokens;

    unsigned myWait;
    semaphore& my_sem;
    semaphore& next_sem;

    unsigned* myBuffer;
    unsigned* nextBuffer;
    unsigned curToken;
public:
    FilterBase( FilterType filter,
                unsigned tot_tokens,
                std::atomic<unsigned>& my_tokens,
                std::atomic<unsigned>& other_tokens,
                unsigned my_wait,
                semaphore& m_sem,
                semaphore& n_sem,
                unsigned* buf,
                unsigned* n_buf )
        : ima(filter), totTokens(tot_tokens), myTokens(my_tokens),
          otherTokens(other_tokens), myWait(my_wait), my_sem(m_sem),
          next_sem(n_sem), myBuffer(buf), nextBuffer(n_buf)
    {
        curToken = 0;
    }

    void Produce( const int );
    void Consume( const int );
    void operator()( const int tid ) {
        if (ima == imaConsumer) {
            Consume(tid);
        } else {
            Produce(tid);
        }
    }
}; // class FilterBase

class ProduceConsumeBody {
    FilterBase** my_filters;
public:
    ProduceConsumeBody( FilterBase** filters ) : my_filters(filters) {}

    void operator()( const int tid ) const {
        my_filters[tid]->operator()(tid);
    }
}; // class ProduceConsumeBody

// send a bunch of non-null "tokens" to consumer, then a nullptr
void FilterBase::Produce( const int ) {
    nextBuffer[0] = 0; // just in case we provide no tokens
    sBarrier.wait();
    while(totTokens) {
        while(!myTokens) {
            my_sem.P();
        }
        // we have a slot available
        --myTokens; // moving this down reduces spurious wakeups
        --totTokens;
        if (totTokens) {
            nextBuffer[curToken & (MAX_TOKENS - 1)] = curToken * 3 + 1;
        } else {
            nextBuffer[curToken & (MAX_TOKENS - 1)] = 0;
        }
        ++curToken;

        utils::Sleep(myWait);
        unsigned temp = ++otherTokens;
        if (temp == 1) {
            next_sem.V();
        }
    }
    next_sem.V(); // final wakeup
}

void FilterBase::Consume( const int ) {
    unsigned myToken;
    sBarrier.wait();
    do {
        while( !myTokens ) {
            my_sem.P();
        }
        // we have a slot available
        --myTokens;
        myToken = myBuffer[curToken & (MAX_TOKENS - 1)];
        if (myToken) {
            REQUIRE_MESSAGE(myToken == curToken * 3 + 1, "Error in received token");
            ++curToken;
            utils::Sleep(myWait);
            unsigned temp = ++otherTokens;
            if (temp == 1) {
                next_sem.V();
            }
        }
    } while(myToken);
    // end of processing
    REQUIRE_MESSAGE(curToken + 1 == totTokens, "Didn't receive enough tokens");
}

// test of producer/consumer with atomic buffer cnt and semaphore
// nTokens are total number of tokens through the pipe
// pWait is the wait time for the producer
// cWait is the wait time for the consumer
void test_producer_consumer( unsigned totTokens, unsigned nTokens, unsigned pWait, unsigned cWait ) {
    semaphore p_sem;
    semaphore c_sem;
    std::atomic<unsigned> p_tokens;
    std::atomic<unsigned> c_tokens(0);

    unsigned c_buffer[MAX_TOKENS];
    FilterBase* my_filters[2]; // one producer, one concumer

    REQUIRE_MESSAGE(nTokens <= MAX_TOKENS, "Not enough slots for tokens");

    my_filters[0] = new FilterBase(imaProducer, totTokens, p_tokens, c_tokens, pWait, c_sem, p_sem, nullptr, &(c_buffer[0]));
    my_filters[1] = new FilterBase(imaConsumer, totTokens, c_tokens, p_tokens, cWait, p_sem, c_sem, c_buffer, nullptr);

    p_tokens = nTokens;
    ProduceConsumeBody body(my_filters);
    sBarrier.initialize(2);
    utils::NativeParallelFor(2, body);
    delete my_filters[0];
    delete my_filters[1];
}

//! \brief \ref error_guessing
TEST_CASE("test binary semaphore") {
    test_binary_semaphore(utils::MaxThread);
}

//! \brief \ref error_guessing
TEST_CASE("test semaphore") {
    for (int sem_size = 1; sem_size <= int(utils::MaxThread); ++sem_size) {
        for (int ex_threads = 0; ex_threads <= int(utils::MaxThread) - sem_size; ++ex_threads) {
            test_semaphore(sem_size, ex_threads);
        }
    }
}

//! \brief \ref error_guessing
TEST_CASE("test producer-consumer") {
    test_producer_consumer(10, 2, 5, 5);
    test_producer_consumer(10, 2, 20, 5);
    test_producer_consumer(10, 2, 5, 20);

    test_producer_consumer(10, 1, 5, 5);
    test_producer_consumer(20, 10, 5, 20);
    test_producer_consumer(64, 32, 1, 20);
}