Search code examples
c++windowsmultithreadingconcurrencymemory-model

Cross-thread visibility of changes to std::vector synchronized only with Win32 events


Suppose I have a std::vector<Item> class member variable where Item is some class with getters and setters. It is created in one thread (#1) but is filled from the other thread (#2) with push_backs. In the end it is read in the thread #1. The access to it is synchronized only with Windows event objects. The event is set to a signaled state when the vector is filled up.

Should I beware of cross-thread visibility issues (getting stale values) in this scenario? If yes, how could these issues be prevented?


Solution

  • Microsoft says waiting on event objects is enough.

    According to MSDN:

    The following synchronization functions use the appropriate barriers to ensure memory ordering:

    • Functions that enter or leave critical sections
    • Functions that signal synchronization objects
    • Wait functions
    • Interlocked functions

    This means if Thread #1 sees the side effect of the event object signaled, it must see the side effect of Thread #2's modification of the vector.