C # multithreaded Tour (1)

Source: Internet
Author: User

Read Catalogue

    • First, Multithreading introduction
    • Second, Join and sleep
    • Third, how the thread works
    • Iv. Threads and processes
    • V. Use and misuse of threads

The original address: C # multithreaded Tour (1)--Introduction and basic concepts

C # multithreaded Tour directory:

C # multithreaded Tour (1)--Introduction and basic concepts

C # multithreaded Tour (2)--Create and start threads

C # multithreaded Tour (3)--thread pool

C # multithreaded Tour (4) A tentative study of--APM

C # multithreaded Tour (5)--Introduction to the synchronization mechanism

C # multithreaded Tour (6)--A detailed description of locks in multiple threads

More articles are being updated, so please look forward to ...

C # multithreaded Tour (1)--Introduction and basic concepts

Back to top one, multithreading introduction

C # supports parallel execution of code through multithreading. A thread is an independently executed path that can be run concurrently with other threads. a C # client program (console,wpf,winows Forms) begins with a separate thread that is created automatically by the CLR and the operating system, which we call the main thread, You can also implement multithreading by creating additional threads.

All of the examples assume that the following namespaces are introduced :

Using System;

Using System.Threading;

1. Preliminary study
1  Class Program 2 {3             static void Main (string[] args) 4             {5                 thread thread = new Thread (writey);//Create a thread 6 C4/>thread. Start ();//Starting a thread 7      8 for                 (int i = 0; i < i++)//main thread execution Loop 9                 {                     Console.Write ("x");                 }12     -                 Console.ReadLine ();             }15             static void Writey () (                 int i = 0; i <; i++)                 {19
   console.write ("Y");                 }21             }22     }

Once started, the IsAlive property of a thread returns true until the thread ends. This thread ends when the delegate passed to the thread's constructor finishes execution. Once this is done, the thread cannot be restarted.

2. Memory Isolation

the CLR allocates its own memory stack to each thread, so local variables can remain detached. In the next example, we define a

Use the local variable method, and then call this method at the same time on both the main thread and the child thread.

1 class Program 2 {3     static void Main (string[] args) 4     {5         new Thread (Go). Start (); 6         Go (); 7         Console.readkey (); 8     } 9     static void Go () One     {ten for         (int i = 0; i < 5; i++) 13
   {14             Console.Write ("Y");         }16     }17}

Because each thread's memory stack has a copy of the quarantined loop variable, it can be inferred that the output is a "y" character .

3. Data sharing

If multiple threads have the same reference to the same object instance, the threads share the data of the object instance. For example:

1 class Program 2 {3     bool do = FALSE; 4     static void Main (string[] args) 5     {6 program         p= new Program (); 7         New Thread (P.go). Start (); 8         P.go (); 9         Console.readkey ();     }11     void Go ()     {         if (!done)             True;17             Console.WriteLine ("Done");         }19     }20}

Because two threads invoke the go method of instance p , they share the done field, and the result is that done prints only once rather than two times.

Static fields provide another way to share data:

1 class ThreadTest  2 {3 static bool done; Static fields is shared between all threads 4 5 static void Main () 6 {7 new Thread (Go). Start (); 8 Go (); 9}10 One-to-one static void Go () {(!done) {done = true; Console.WriteLine ("Done"); }14}15}
4. Thread Safety

These two examples illustrate another important concept: thread safety is indeed uncertain :d one may be printed two times (albeit unlikely). When we exchange the order of the statements in the Go method, the chance of printing two done is significantly increased.

1 class Program 2 {3     static bool do = FALSE; 4     static void Main (string[] args) 5     {6 program         p = new Pr Ogram (); 7         New Thread (P.go). Start (); 8         P.go (), 9         Console.readkey (),     }11     void Go () (         !done)             Console.WriteLine ("Done"); + done             = true;18         }19     }20}

The problem with this place is that thread a threads B is set to do equal to True before entering the if condition judgment, all A has the opportunity to print out "Done".

Improved mode gets an exclusive lock (exclusive lock) when reading \ Writing a public field. C # provides the keyword lock.

1 class Program 2 {3     static bool do = FALSE; 4     static readonly object locker = new Object (); 5     static Voi D Main (string[] args) 6     {7         new Thread (Go). Start (); 8         Go (); 9         Console.readkey ();     }11-     static void Go (         Locker)         {16             if (!done)                 { Console.WriteLine ("Done"); do                 = true;20             }21         }22     }23}

When two threads preempt a lock at the same time (in this case,locker), a thread waits, or blocks, to know that the lock is released. In this case, the lock guarantees that only one thread can enter the critical area of the code at a time, and then "done" is only printed once. Code protected in this uncertain multi-threaded context is called thread safety.

Note: In multi-threading, sharing data is the main cause of complex causes, and it can create confusing errors. Even though it's basic, keep it as simple as possible.

A thread that does not consume CPU resources when it is blocked .

Back to TopSecond,Join and Sleep 1.Join

By calling a thread's Join method, you can wait for another thread to end. For example:

1 static void Main (string[] args) 2 {3     thread t = new Thread (Go); 4     T.start (); 5     T.join (); 6     Console.writ Eline ("Thread T has ended!"); 7     Console.readkey (); 8  9}10 static void Go (     int i = 0; i <; i++) {         CONSOLE.WR Ite ("Y");     }16}

This will print the character "Y" more than once, then immediately print "Thread T has ended!" . Join has multiple overloaded methods, and you can add a parameter,milliseconds or TimeSpan, to the Join method. If the thread ends, the Join method returns Trueand returns false if the line blocks until those .

2.Sleep

Thread.Sleep pauses the current thread for a specified period of time:

Thread.Sleep (timespan.fromhours (1));//sleep an hour .

Thread.Sleep (+);//sleep

When a thread is suspended using Sleep or Join, the thread is blocked and does not consume CPU resources.

Thread.Sleep (0) immediately discards the thread's time slice and proactively surrenders the CPU to other threads. The new method of the Framework 4.0 Thread.yield () method does the same thing, except that when it is only in the same process, the time slice is discarded.

Sleep (0) or Yield () is sometimes useful for improving product performance. And they are also diagnostic tools that can help uncover thread-safety issues;

Inserting Thread.yield () anywhere in the code can cause a bug.

Back to the top three, how the thread works

1. multithreading is managed internally by a thread scheduler , a function that the CLR often entrusts to the operating system.

A thread scheduler ensures that all active threads are properly allocated during execution, waiting or blocking threads (such as an exclusive lock or waiting for user input) that do not consume CPU resources.

2. on a single-core computer, a thread scheduler lets the time slice switch between each active thread. under the Windows operating system, thread switching typically has a time shard of ten microseconds, much larger than the CPU's overhead time (typically less than 1 microseconds).

3. On a multicore computer, multithreading implements a mix of time slices and real concurrency, with different threads executing code on different CPUs at the same time . There are still some time slices, because the operating system needs to serve its own thread, including other threads of the application.

4. when the execution of a thread is interrupted by an internal factor, such as a time slice, it says that the thread is preemptive. In most cases, a thread cannot control when and where it is preempted.

Back to top four, threads and processes

A thread is similar to an operating system process that your application is running. Similar to a process running in parallel on a single computer, threads run in parallel in a separate process. Processes are completely isolated, and threads are isolated to some extent. A thread that runs under the same application shares heap memory. In a way, this is why threads are so useful: a thread can retrieve data in the background, such as while another thread is displaying the data.

Back to top v. Use and misuse of threads

Multithreading has many uses, and the following are the most common:

Maintain a responsive user interface

ByRunning time-consuming tasks on a parallel "worker" thread, the main UI thread can perform keyboard or mouse events idle.

Make the most efficient use of other threads that are blocking the CPU

This is useful when a thread is waiting for a response from another computer or hardware. When a thread executes a task, it blocks, and the other threads can use the computer exactly.

Parallel programming

If the workload is shared with multiple threads that are executing the "conquer" policy, the code can execute faster in a multi-core or multi-process centralized calculation.

Predictive execution

On multicore machines, you can sometimes improve performance by predicting something that needs to be done, and then doing it in advance. LINQPad uses this technique to improve the creation of queries. One variant is to run many parallel algorithms to handle the same tasks. Whichever completes the first "wins"- This is very effective when you don't know in advance which algorithm executes faster.

Allow simultaneous execution of requests

On one server , client requests can arrive in parallel, so parallel processing is required. If you use asp.net,wcf,web Service or Remoting, the. NET Framework automatically creates threads. This is also useful on the client (for example, to handle point-to-point net working, or multiple requests from the user).

For example, ASP . NET and WCF technology, you may not even notice that unless you access the appropriate locking, you violate thread-safe shared data (presumably through a static field).

Multithreading can lead to a number of problems. The biggest problem is that multithreading increases complexity. Many threads themselves do not create complexity, but rather because of the interplay between threads (especially by sharing data). This applies to whether this interaction is intentional, and this can result in a long period of development and a persistent sensitivity and non-reproducible bug. For this reason, mutual influence needs to be minimized. adhere to and improve reliable design as much as possible. This article focuses on dealing with these complexities, removing the interaction that does not have to say much.

A good strategy is to encapsulate multithreaded logic into reusable classes that can be tested independently. This Framework itself provides a number of advanced threading constructors, which we'll cover later.

When a thread schedules and switches threads, it causes resource and CPU consumption (when the number of active threads is the amount of excess CPU cores)- and there is a create / destroy loss. Multithreading usually increases the speed of your application - but it can even slow the application if it is overused or inappropriate. For example, when hardware I/O is involved, there are two threads that run the task serially at a time faster than a single execution of the ten parallel threads. (in the wait and pulse signals, we describe how to implement a producer / consumer queue to implement this function.) )

Reference: "C # 4.0 in a nutshell"

C # multithreaded Tour (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.