forked from dotnet/machinelearning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_barrier.h
More file actions
66 lines (50 loc) · 1.44 KB
/
simple_barrier.h
File metadata and controls
66 lines (50 loc) · 1.44 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#ifndef _SIMPLE_BARRIER_H_
#define _SIMPLE_BARRIER_H_
#include <atomic>
#include <condition_variable>
#include <thread>
namespace lda
{
class SimpleBarrier
{
public:
SimpleBarrier(unsigned int n) :barrier_size_(n), num_of_waiting_(0), rounds_(0)
{};
void reset()
{
throw "not implemented yet.";
}
bool wait()
{
std::unique_lock<std::mutex> lock(mutex_);
if (num_of_waiting_.fetch_add(1) >= barrier_size_ - 1)
{
cond_.notify_all();
num_of_waiting_.store(0);
rounds_.fetch_add(1);
return true;
}
else
{
unsigned int i = rounds_.load();
cond_.wait(lock, [&]{return i != rounds_.load(); });
return false;
}
}
~SimpleBarrier()
{
num_of_waiting_ = 0;
rounds_ = 0;
}
protected:
const unsigned int barrier_size_;
std::atomic<unsigned int> num_of_waiting_;
std::atomic<unsigned int> rounds_;
std::condition_variable cond_;
std::mutex mutex_;
};
}
#endif // _SIMPLE_BARRIER_H_