-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathThreadBarrier.h
More file actions
81 lines (73 loc) · 1.4 KB
/
ThreadBarrier.h
File metadata and controls
81 lines (73 loc) · 1.4 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* ThreadBarrier.h
*
* Created on: Jul 3, 2013
* Author: fb
*/
#ifndef THREADBARRIER_H_
#define THREADBARRIER_H_
#include <atomic>
#include <unistd.h>
namespace LSAP
{
/**
* realizes a barrier with thread kill for std:threads
*/
class ThreadBarrier
{
public:
/**
* creates a barrier which waits for n threads for continuation
* @param n number of threads
*/
ThreadBarrier(const size_t n, const bool & purespin = false, const size_t sleeptime = 5) :
_n(n), _nwait(0), _step(0), _kill(false), _spin(purespin), _sleep(true), _sleeptime(sleeptime)
{
}
virtual ~ThreadBarrier()
{
}
void sleep() { if ( !_spin) _sleep = true; }
void wakeup() { if ( !_spin) _sleep = false; }
const bool operator()()
{
// return true if kill-signal
if (_kill.load())
return true;
unsigned int step = _step.load();
if (_nwait.fetch_add(1) == _n - 1)
{
_nwait.store(0);
_step.fetch_add(1);
}
else
{
// waiting
while (_step.load() == step)
{
if (_sleep) usleep(_sleeptime);
// return true if kill-signal
if (_kill.load())
return true;
}
}
return false;
}
/**
* set kill flag for return value
*/
void kill()
{
_kill.store(true);
}
protected:
size_t _n;
std::atomic<unsigned int> _nwait;
std::atomic<unsigned int> _step;
std::atomic<bool> _kill;
bool _spin;
bool _sleep;
size_t _sleeptime;
};
} /* namespace LSAP */
#endif /* THREADBARRIER_H_ */