Do I need to protect read access to an STL container in a multithreading environment?

前端 未结 8 1732
逝去的感伤
逝去的感伤 2020-11-29 10:01

I have one std::list<> container and these threads:

  • One writer thread which adds elements indefinitely.

  • One reader/writer thread which re

相关标签:
8条回答
  • 2020-11-29 10:22

    Whether or not size() is safe (for the definition of "safe" that you provide) is implementation-dependent. Even if you are covered on your platform, for your version of your compiler at your optimization level for your version of thread library and C runtime, please do not code this way. It will come back to byte you, and it will be hell to debug. You're setting yourself up for failure.

    0 讨论(0)
  • 2020-11-29 10:29

    You should consider some SLT implementation might calculate the size when called.
    To overcome this, you could define a new variable

    volatile unsigned int ContainerSize = 0;
    

    Update the variable only inside already protected update calls, but you can read / test the variable without protection (taking into account you don't need the exact value).

    0 讨论(0)
提交回复
热议问题