Use standard C++
In your code, you use EnterCriticalSection()
and LeaveCriticalSection()
functions of Microsoft's WinAPI.
These have wto major inconveniences: first they are not portable, second they are not safe: what would happen if an exception would cause the thread to leave ReadData()
in an unexpected fashion ? You might end-up with a critical section that appears to windows not to be left, starving all the other threads !
The standard C++ alternative using a lock_guard
on a mutex
, as demonstrated by Werner, is much safer: first it is portable across platforms, but in addition, it implements the RAII idiom, which ensures that if there's an unexpected exception, the lock_guard
is destroyed when the function is left, causing the mutex
to be released.
Use of atomic might not be sufficient
Very often, people are tempted to use atomics because they avoid data races and give the impression that it will address all the thread synchronisation issues.
Unfortunately, this is not true. As soon as you use several atomics, you might make assumption about the overall consistency, whereas in reality things could happen differently and cause very nasty bugs. Creating lock-free algorithms and data-structures is extremely challenging and difficult. I therefore recommend strongly to read Anthony William's excellent book "C++ concurrency in action" : he explores in full depth all the related aspects.
Other alternatives
In your question you refer to a vector. Maintaining a concurrent thread safe vector is very difficult, because basically, whenever the vector's capacity has to be extended, a reallocation might occur, invalidating all the iterators and pointers to this vector, wherever they are used. Fortunately, there are some thread safe implementations like Microsoft's Parallel Pattern Library.
On the other hand, if you use a vector only to store the lines of the file and process them sequentially, you mays as well consider using a queue, with the advantage of being able to use one of the many thread safe implementations available, such as for example boost.