-
Notifications
You must be signed in to change notification settings - Fork 0
/
RingBufferIntelTBB.cpp
56 lines (46 loc) · 1.2 KB
/
RingBufferIntelTBB.cpp
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
#include <iostream>
#include <vector>
#include <tbb/concurrent_queue.h>
#include <tbb/parallel_for.h>
template < typename T >
class RingBuffer
{
public: RingBuffer(size_t capacity): buffer(capacity)
{
}
void push(const T & item)
{
buffer.push(item);
}
T pop()
{
T item;
buffer.try_pop(item);
return item;
}
private: tbb::concurrent_bounded_queue < T > buffer;
};
int main()
{
const size_t bufferSize = 10;
const size_t numThreads = 4;
RingBuffer < int > ringBuffer(bufferSize);
tbb::parallel_for(tbb::blocked_range < size_t > (0, numThreads), [ & ](const tbb::blocked_range < size_t > & range)
{
for (size_t i = range.begin(); i != range.end(); ++i)
{
int item = i * 10;
ringBuffer.push(item);
std::cout << "Thread " << i << " pushed item: " << item << std::endl;
}
});
tbb::parallel_for(tbb::blocked_range < size_t > (0, numThreads), [ & ](const tbb::blocked_range < size_t > & range)
{
for (size_t i = range.begin(); i != range.end(); ++i)
{
int item = ringBuffer.pop();
std::cout << "Thread " << i << " popped item: " << item << std::endl;
}
});
return 0;
}