I am currently refactoring some code I found in the nvidia hardware encoder for compressing video images. The original question is here: wondering if I can use stl smart pointers for this
Based on the answers, I have updated my code as follows:
Based on the answers and the comments, I have tried to make a thread-safe buffer array. Here it is. Please comment.
#ifndef __BUFFER_ARRAY_H__
#define __BUFFER_ARRAY_H__
#include <vector>
#include <mutex>
#include <thread>
template<class T>
class BufferArray
{
public:
class BufferArray()
:num_pending_items(0), pending_index(0), available_index(0)
{}
// This method is not thread-safe.
// Add an item to our buffer list
// Note we do not take ownership of the incoming pointer.
void add(T * buffer)
{
buffer_array.push_back(buffer);
}
// Returns a naked pointer to an available buffer. Should not be
// deleted by the caller.
T * get_available()
{
std::lock_guard<std::mutex> lock(buffer_array_mutex);
if (num_pending_items == buffer_array.size()) {
return NULL;
}
T * buffer = buffer_array[available_index];
// Update the indexes.
available_index = (available_index + 1) % buffer_array.size();
num_pending_items += 1;
return buffer;
}
T * get_pending()
{
std::lock_guard<std::mutex> lock(buffer_array_mutex);
if (num_pending_items == 0) {
return NULL;
}
T * buffer = buffer_array[pending_index];
pending_index = (pending_index + 1) % buffer_array.size();
num_pending_items -= 1;
return buffer;
}
private:
std::vector<T * > buffer_array;
std::mutex buffer_array_mutex;
unsigned int num_pending_items;
unsigned int pending_index;
unsigned int available_index;
// No copy semantics
BufferArray(const BufferArray &) = delete;
void operator=(const BufferArray &) = delete;
};
#endif
My question is whether I am breaking some C++ good practice recommendations here? Also, I am expending the class so that it can be accessed and used my multiple threads. I was wondering if there is anything that I might have missed.