Subj : Re: Challenge: Multithreading & Synchronization To : comp.programming.threads From : Uenal Mutlu Date : Thu May 19 2005 04:30 pm "Maciej Sobczak" wrote > Uenal Mutlu wrote: > > What should be thread-safe, in fact, is the overall state of your program, not the > state of each separate brick. The scope of this overall state is usually > much broader than a single value object. Don't think in terms of > "independent objects". If they were independent, you wouldn't put them > all in the same program. Ok, a much better term would be "independently accessible objects". If one is locked then any other thread wanting to use one of the non-locked objects can still continue its job; so it is not forced to wait. Of course your program will work even with just only 1 global mutex for everything too, but by using a finer locking granularity you could get better performance. It of course depends on the data. We've usually the following cases: // case0: exclusive access to all objects; the whole app has just 1 mutex: void f() { Locker L(app.m); for (size_t i = 0; i < vec.size(); i++) { // manipulate vec } } // case1: exclusive access to an object: void f() { Locker L(vec.m); for (size_t i = 0; i < vec.size(); i++) { // manipulate vec } } // case2: shared access to an object: void f() { for (size_t i = 0; i < vec.size(); i++) { Locker L(vec.m); // manipulate vec } } With many threads and high concurrency case2 mostly would lead to the fastest performance, although it might look counter-intuitive. This case would be a good choice for a realtime application. But mostly case1 is sufficient. Case0 usually would lead to the slowest performance. If there are independently accessible objects then in a hi-speed time criticial (highly concurrent) app one better should try case1 first and then try to extend it to use case2. For usual GUI apps case1 is mostly the better choice. Case0 should be used only when porting a single threading app to multithreading in the first stage, in later stages it should be extended to use case1. That's my philosophy. .