Threads 615 example 16 4 does something slightly

Info icon This preview shows pages 639–642. Sign up to view the full content.

View Full Document Right Arrow Icon
Threads | 615
Image of page 639

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

View Full Document Right Arrow Icon
Example 16-4 does something slightly unusual with the Thread con- structor. Our Go method now requires two arguments—the StringBuilder and the name—but Thread doesn’t provide a way to pass in more than one argument; we get to choose an argument count of either zero or one. So we’re using a lambda here to provide a zero-ar- gument method for Thread , and that lambda passes the two arguments into Go , including the new StringBuilder argument. It has also enabled us to declare that the Go method is expecting the name to be a string , rather than the less specific object type used in the previous example. This technique doesn’t have anything to do with threading; it’s just a useful trick when you find yourself confronted with an API that takes a delegate that doesn’t have enough arguments. (And it’s not the cause of the problem here. Less concise ways of passing the object in would have had the same problem, and so would the use of multiple methods, which Example 16-1 illustrated.) Example 16-4. Local variables, but shared state using System; using System.Threading; using System.Text; class Program { static void Main(string[] args) { StringBuilder result = new StringBuilder(); // Sharing the StringBuilder between threads. BAD! Thread t1 = new Thread(() => Go(result, "One")); Thread t2 = new Thread(() => Go(result, "Two")); t1.Start(); t2.Start(); Go(result, "Main"); t1.Join(); t2.Join(); Console.WriteLine(result); } static void Go(StringBuilder sb, string name) { 616 | Chapter 16: Threads and Asynchronous Code
Image of page 640
for (int i = 0; i < 100; ++i) { // All threads using the same StringBuilder - BAD! sb.AppendFormat("{0}: {1}", name, i); sb.AppendLine(); } } } By the way, you’ll have noticed that this code calls Join on both Thread objects. The Join method blocks until the thread has finished—this code needs to do that because it prints the output only once the threads are done. This is a simple example of coor- dinating operations across multiple threads. However, it’s not sufficient to avoid prob- lems here. Looking at the output, it’s clear that all is not well. Here are the first few lines, running on a quad-core system: Main: One: Two: 00 Main: 1 2 MainTwo: 3 Main: 1 2 2 Two: 3One: Two: 4 Two: One: 6Two: One: 7 One: 8 : One: 9 That’s a whole lot more chaotic than the previous examples, which merely scrambled the order of the lines, and lost the odd increment. The reason this has gone more ob- viously wrong is that with the earlier examples, our attempt to observe the system profoundly changed its behavior. (That happens a lot with multithreaded code.) The calls to Console.WriteLine were imposing some order on the system, because the .NET Framework was forcing the threads to take it in turns when printing their output— that’s why we don’t get lines mixed up with one another. But Example 16-4 does all of its work in memory using a StringBuilder , and since it calls Console.WriteLine just once when it’s done, to print the results, nothing is forcing things to happen in any particular order, and so we can see the chaos in full effect.
Image of page 641

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

View Full Document Right Arrow Icon
Image of page 642
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