999 Subj : Re: Challenge: Multithreading & Synchronization To : comp.programming.threads From : Uenal Mutlu Date : Sat May 21 2005 01:45 am "Maciej Sobczak" wrote > Uenal Mutlu wrote: > > Another alternative: > > > > > > mutex gm; > > > > void f1() > > { > > Locker L(gm); > > print("First name : Maciej"); > > print("Family name: Sobczak"); > > print("Profession : Programmer"); > > } > > > > void f2() > > { > > Locker L(gm); > > print("First name : Cody"); > > print("Family name: Hacker"); > > print("Profession : Programmer"); > > } > > Great! > (I assume that gm is used *only* for the purpose of ensuring correct > printouts) If one thread is in f1() then the other thread will wait until gm gets cleared, the same is true for f2(). gm can be seen as a flag: if it is set then the thread internally waits (sleeps) until the flag is cleared. It gets set (after a possible waiting for it be cleared first by the other thread) in the constructor of Locker, and cleared atomatically in the destructor of the Locker class when L gets out of scope (ie. at function end). That's the usual job of a mutex. > So - what this every_object_has_a_mutex_inside concept gives me then? It is best used in an OOP (object oriented programming) environment. If you know of the power of constructor and destructor of a class then simply think of each class also having Lock() and Unlock() methods: In a MT application you then could lock things at the object level (instead of at the application level), because the mathematical equation is: "Lock exactly that less as necessary, neither too much nor too less" to get the best application performace. And this you can do best if you can lock individual objects; you just lock only those objects which you need, not more. If you unneccessarily lock more objects then you are unneccessarily blocking those other threads which would like to use these objects. By this method you also have the flexibility to build groups on the fly, ie. dynamically forming up a group of related objects for the purpose of modifying the members of the group as a whole. Such a group of related objects you do lock by simply locking each member of the group in the right order (cf. deadlock theorem). The alternative would be to use just 1 mutex for the group, but I personally find it better if each object can be locked individually, because it is a general solution. . 0