开发者

Odd issue with std::map and thread safety

开发者 https://www.devze.com 2023-02-15 10:53 出处:网络
This isn\'t so much of a problem now as I\'ve implemented my own collection but still a little curious on this one.

This isn't so much of a problem now as I've implemented my own collection but still a little curious on this one.

I've got a singleton which provides access to various common components, it holds instances of these components with thread ID's so each thread should (and does, I checked) have it's own instance of the component such as an Oracle database access library.

When running the system (which is a C++ library being called by a C# application) with multiple incoming requests everything seems to run fine for a while but then it crashes out with an AccessViolation e开发者_JAVA百科xception. Stepping through the debugger the problem appears to be when one thread finishes and clears out it's session information (held in a std::map object) the session information held in a separate collection instance for the other thread also appears to be cleared out.

Is this something anyone else has encountered or knows about? I've tried having a look around but can't find anything about this kind of problem.

Cheers


Standard C++ containers do not concern themselves with thread safety much. Your code sounds like it is modifying the map instance from two different threads or modifying the map in one thread and reading from it in another. That is obviously wrong. Use some locking primitives to synchronize the access between the threads.


If all you want is a separate object for each thread, you might want to take a look at boost::thread_specific_ptr.


How do you manage giving each thread its own session information? Somewhere under there you have classes managing the lifetimes of these objects, and this is where it appears to be going wrong.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号