0

I plan to have 2 threads.

Thread 1 will only push back new items into the vector.

Thread 2 will only get item of the vector by index, namely v[i].

Is this thread safe?

If this is not, is there any better solution? What I want is not to block thread 1, i.e. the push back. It's ok to have a short sleep or block or delay for thread 2 to get information from the vector.

Edit: The answer is no, and probably a fixed size array will be a solution.

Cuero
  • 1,169
  • 4
  • 21
  • 42
  • Can you impose a limit on the size of the vector? Because one problem of vector is that push_back can invalidate all pointers. (in all implementation that happens only when size()=capacity()). So to get an efficient version the solution is either to fix the vector size, or use a list instead. – Oliv Aug 21 '18 at 06:58
  • 1
    Short answer: no. Access to a elements of a vector need to be synchronised if the vector is being modified at all. Even more so when one of the threads potentially resizes the vector (like your thread 1). – Peter Aug 21 '18 at 06:58
  • 1
    I’m putting this as a comment because it doesn’t explicitly answer the question. However, you should use a lock. I don’t think the standard guarantees the order of, e.g. updating the size and creating the element on push_back. It sounds like you’re describing a classic use of a semaphore. – Mike Lui Aug 21 '18 at 07:00

0 Answers0