Multithreaded access to memory
Good morning,
Say I have some 6 different threads, and I want to share the same data with each of them at the same time. Can I make a class variable with the data I want to share and make each thread access that memory concurrently withou开发者_如何学Pythont performance downgrade, or is it preferable to pass a true copy of the data to each thread?
Thank you very much.
It depends entirely on the data;
- if the data is immutable (or mutable but you don't actually mutate it), then chuck all the threads at it - great
- if you need to mutate it, but no two threads will ever depend on the data mutated by another - great
- if you need to mutate it, and there are conflicts but you can sensibly synchronize access to the data such that there is no risk of two threads deadlocking etc - great, but not always trivial
- if it is not safe to make any assumptions, then a true clone of the data is the safest approach, but has the most overhead in terms of data duplication; if the data is cheap to copy, this may be fine - and indeed may outperform synchronization
- if the threads do co-depend on each other, then you have no option other than to figure out some kind of sensibly locking strategy; again - to stress: deadlocks are a problem here - some ideas:
- always provide a timeout when obtaining a lock
- if you need to lock two items, it may help to try locking both eagerly (rather than locking one at the start, and the other after you've done lots of changes) - then you can simply release and re-take the locks, without having to either undo changes, or put the changes back into a particular state
精彩评论