Mark Miles
Mark Miles

Reputation: 706

c++ vector assign() method fails frequently

I have a vector of floats that is resized and emptied multiple times during the runtime using the assign() method, but it fails every time I switch to a smaller size throwing an exception Vector subscript out of range.

Declarations:

std::vector<float> buffer;
size_t size, c;

Setting size and deleting old content:

void SetBuffersize(size_t sz)
{
  // Resize vector
  // buffer.resize(sz); // really not needed?

  // Delete old content
  buffer.assign(sz, 0);
}

There's a thread running that continuously accesses this vector:

void Process()
{
  if (++c >= size) c = 0;
  float out = buffer[c];
  // do something with out;
}

And another thread can resize the buffer:

void ChangeStatus(int n)
{
  size = size_table[n];
  SetBuffersize(size);
}

I solved by adding a flag that blocked the Process() function while the vector is being resized. Is there a better solution to avoid the overhead of an extra if statement in a real-time thread?

Upvotes: 4

Views: 316

Answers (1)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36431

It seems that you always have a race condition :

  • Suppose size=10 and c=5
  • Process evaluates the condition as false
  • ChangeStatus clears the vector
  • Process tries to get buffer[c] on a vector of size=0

You must take care when accessing data concurrently. What you need is a form of atomicity, take a look at semaphores, locks, etc. If you need performance you can look at spin locks. http://en.wikipedia.org/wiki/Spinlock

Upvotes: 1

Related Questions