Listt is not unusual most types in the net framework

Info icon This preview shows pages 660–662. Sign up to view the full content.

View Full Document Right Arrow Icon
List<T> is not unusual. Most types in the .NET Framework class library make no guarantees of thread safety for instance members. We could add similar documentation to our MostRecentlyUsed class, declaring that it does not make any guarantees either. In fact, that might well be the best option—it’s very difficult for an individual class to guarantee to work correctly in all possible mul- tithreading scenarios. Only the application that uses the class really knows what con- stitutes correct behavior. For example, it might be necessary for a MostRecentlyUsed object to be kept in sync with some other object, in which case the application is going to have to manage all synchronization itself, and there’s nothing useful that our class could do on its own. This is one reason why the lack of thread safety guarantees is so widespread in the class libraries—there isn’t a good general-purpose definition of thread-safe for individual types. If we decide to make it the application’s problem, how would that look? We don’t have a real application here, only a test, so our test code would need to synchronize its calls into our object. Example 16-12 shows a suitably modified version of the test method 636 | Chapter 16: Threads and Asynchronous Code
Image of page 660

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
from Example 16-10 . (Note that Example 16-11 adds code that also uses the same object, so you might think we need to make a similar modification there. However, it waits until all the test threads have finished before touching the object, so its reads won’t overlap with their writes, making locking superfluous. Therefore, Exam- ple 16-12 is sufficient in this case.) Example 16-12. Synchronization in the calling code static void TestMru(MostRecentlyUsed mru) { Random r = new Random(Thread.CurrentThread.ManagedThreadId); string[] items = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight" }; for (int i = 0; i < Iterations; ++i) { lock (mru) { mru.UseItem(items[r.Next(items.Length)]); } } } The only modification here is to wrap the call to the MostRecentlyUsed type’s UseItem method with a lock block. The C# lock syntax generates some code that uses the Monitor class, along with some exception handling. Here’s what the lock block in Example 16-12 is equivalent to: MostRecentlyUsed referenceToLock = mru); bool lockAcquired = false; try { Monitor.Enter(referenceToLock, ref lockAcquired); mru.UseItem(items[r.Next(items.Length)]); } finally { if (lockAcquired) { Monitor.Exit(referenceToLock); } } (This is what C# 4.0 generates. Older versions do something slightly simpler that mis- handles an obscure and unusual failure mode. But the basic idea is the same in either case. The generated code copies the mru reference into a separate variable to ensure correct operation even if the code inside the lock block were to change mru .) The documentation says that Monitor.Enter acquires an exclusive lock on the object passed as the first argument, but what exactly does that mean? Well, the first thread to do this will find that Monitor.Enter returns immediately. Any other threads that try to make the same call on the same object will be made to wait— Monitor.Enter
Image of page 661
Image of page 662
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern