I found a great producer/consumer double buffer example in this question. However, instead of setting T to "int", I want to use "int *". Unfortunately, it doesn't work, and I keep getting segmentation faults when writing to the buffer. The code below is what I've tried. Would anyone mind telling me how to solve that problem?
void processing(DoubleBuffer<int *> *const buf, int num_elts)
{
std::thread producer([&]() {
for (int i = 0; i != num_elts; ++i) {
int **item = buf->start_writing();
if (item != nullptr) { // Always true
**item = i;
}
buf->end_writing();
}
});
/*
std::thread consumer([&]() {
int prev = -1;
for (int i = 0; i != 10; ++i) {
int* item = *buf->start_reading();
std::cout << "Consumer: " << item << std::endl;
if (item != nullptr) {
assert(*item > prev);
prev = *item;
std::cout << "prev: " << prev << std::endl;
}
buf->end_reading();
}
});
*/
producer.join();
//consumer.join();
}
int main(void) {
int* buffer_a;
int* buffer_b;
int num_elts = 10;
ProducerConsumerDoubleBuffer<int *> buf;
buf.m_buf[0] = buffer_a + num_elts;
buf.m_buf[1] = buffer_b + num_elts;
processing(&buf, num_elts);
}
I modified the class from the post you linked to work better with pointer types. Playing around with the member variables seemed wrong, so I added a malloc to the constructor to avoid segfaults.