Subj : Re: Challenge: Multithreading & Synchronization To : comp.programming.threads From : Maciej Sobczak Date : Fri May 20 2005 06:47 pm Uenal Mutlu wrote: >>What about the multithreaded program, where all threads use stdout to >>log their actions? >> >>puts("I'm doing this."); >>puts("I'm doing that."); >> >>Which "case" would you apply here? > > You have to ask yourself especially the following question: > "which object(s) am I sharing among multiple threads?" The terminal? > Then the solution will be simple. Tell me! In fact, this trap is not about "which object are you sharing", but about what is the sequence of activities you want to perform. This is exactly what you don't see. > It works. What do you think does "exclusive access to the object" mean? It is not the question of what it does mean, but what it doesn't. > Try this: > > void f() > { > Locker L(vec.m); > for (size_t i = 0; i < vec.size(); i++) > cout << vec[i].myfield << ... > } Above, locking on the vector is not sufficient, because it does *not* guarantee that the vector's content will be printed continuously on the output, because there might be other functions that will print something else at the same time (other vectors?), giving you something between garbage and core dump, inclusive. Again - think in terms of actions, not in terms of objects (multithreading is about "doing", not about "values"). Then you will maybe discover that your concept of embedding mutexes in all value objects brings you nowhere. But sadly speaking, I doubt in any chance of such happy end. -- Maciej Sobczak : http://www.msobczak.com/ Programming : http://www.msobczak.com/prog/ .