C ++ vector assign () method often fails

I have a vector with floats that changes several times at runtime using the assign () method, but it fails every time I switch to a smaller size, throwing an exception Vector subscript out of range.

Ads:

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

Set size and delete old content:

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

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

A thread works there 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 decided by adding a flag that blocked the function Process()when resizing the vector. Is there a better solution to avoid the overhead of an additional operator ifin a real-time stream?

+4
1

, :

  • , = 10 c = 5
  • Process false
  • ChangeStatus
  • Process buffer[c] size = 0

. , , .. , . http://en.wikipedia.org/wiki/Spinlock

+1

Source: https://habr.com/ru/post/1569415/


All Articles