简体   繁体   中英

Intuitive thread safety

After attempting concurrency in my 3D game project, I am beginning to wonder whether it's possible to implement thread safety in a way that's intuitive, clean, and implicit if possible. I don't like having to explicitly lock/unlock mutexes just to access a resource - I'd much rather a solution which is completely hidden from the code that actually does the work. Is there any design pattern or structure which allows this in C++11?

A specific example of a situation where I would like this implemented is detailed below.

Class 1: Has a shared resource (a std::unordered_map ), which holds std::shared_ptr s to Class 3 instances. This class accesses these shared resources.

Class 2: Has a function which is run in it's own thread. This function accesses the shared resources from Class 1 (including accessing Class 3 instances).

Class 3: Functions of this class are accessed by both threads. Either thread may read/write.

Any suggestions? Perhaps the real problem here more likely my design which is making thread safety impractical?

There are a crap load of concurrency patterns and idioms. Nothing however so generic you can just forget about all synchronization with one exception: immutable data types. If nothing ever writes to a value then threads don't need to synchronize their access because you can only data race if you're someone is writing.

This includes reference counts. If you're using a reference counted pimpl implementation in your value types then the reference count will have to be written on construction and deletion. Most often this is done with atomic operations which are faster than mutex locks or semaphors but can carry their own issues.

There's copy/modify/swap. Copy the data from an immutable, shared value. Modify the copy. Swap with the immutable value. Look out for the ABA problem.

There's message passing rather than using shared data.

Finally (just what I can think of off the top of my head that is) there's wrapping up shared values into an object that does most of the synchronization stuff for you with some proxy magic. Facebook released one in their folly lib: https://github.com/facebook/folly/blob/master/folly/docs/Synchronized.md This may simplify a lot of already simple issues but isn't a catch-all answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM