forked from cryfs/cryfs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadsafeRandomDataBuffer.h
More file actions
80 lines (64 loc) · 2.67 KB
/
ThreadsafeRandomDataBuffer.h
File metadata and controls
80 lines (64 loc) · 2.67 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
#pragma once
#ifndef MESSMER_CPPUTILS_RANDOM_THREADSAFERANDOMDATABUFFER_H
#define MESSMER_CPPUTILS_RANDOM_THREADSAFERANDOMDATABUFFER_H
#include "../data/Data.h"
#include "../assert/assert.h"
#include "RandomDataBuffer.h"
#include <boost/thread.hpp>
namespace cpputils {
//TODO Test
class ThreadsafeRandomDataBuffer final {
public:
ThreadsafeRandomDataBuffer();
size_t size() const;
void get(void *target, size_t numBytes);
void add(const Data& data);
void waitUntilSizeIsLessThan(size_t numBytes);
private:
size_t _get(void *target, size_t bytes);
RandomDataBuffer _buffer;
mutable boost::mutex _mutex;
boost::condition_variable _dataAddedCv;
// _dataGottenCv needs to be boost::condition_variable and not std::condition_variable, because the
// RandomGeneratorThread calling ThreadsafeRandomDataBuffer::waitUntilSizeIsLessThan() needs the waiting to be
// interruptible to stop the thread in RandomGeneratorThread::stop() or in the RandomGeneratorThread destructor.
boost::condition_variable _dataGottenCv;
DISALLOW_COPY_AND_ASSIGN(ThreadsafeRandomDataBuffer);
};
inline ThreadsafeRandomDataBuffer::ThreadsafeRandomDataBuffer(): _buffer(), _mutex(), _dataAddedCv(), _dataGottenCv() {
}
inline size_t ThreadsafeRandomDataBuffer::size() const {
boost::unique_lock<boost::mutex> lock(_mutex);
return _buffer.size();
}
inline void ThreadsafeRandomDataBuffer::get(void *target, size_t numBytes) {
size_t alreadyGotten = 0;
while (alreadyGotten < numBytes) {
size_t got = _get(static_cast<uint8_t*>(target)+alreadyGotten, numBytes);
alreadyGotten += got;
ASSERT(alreadyGotten <= numBytes, "Got too many bytes");
}
}
inline size_t ThreadsafeRandomDataBuffer::_get(void *target, size_t numBytes) {
boost::unique_lock<boost::mutex> lock(_mutex);
_dataAddedCv.wait(lock, [this] {
return _buffer.size() > 0;
});
size_t gettableBytes = (std::min)(_buffer.size(), numBytes);
_buffer.get(target, gettableBytes);
_dataGottenCv.notify_all();
return gettableBytes;
}
inline void ThreadsafeRandomDataBuffer::add(const Data& data) {
boost::unique_lock<boost::mutex> lock(_mutex);
_buffer.add(data);
_dataAddedCv.notify_all();
}
inline void ThreadsafeRandomDataBuffer::waitUntilSizeIsLessThan(size_t numBytes) {
boost::unique_lock<boost::mutex> lock(_mutex);
_dataGottenCv.wait(lock, [this, numBytes] {
return _buffer.size() < numBytes;
});
}
}
#endif