Introduction to multithreading and parallel computing under. NET (2) Basic thread knowledge

Source: Internet
Author: User

Reprinted -- original address: http://www.cnblogs.com/lovecindywang/archive/2009/12/25/1632213.html

First, let's take a look at how to create a thread:

Console.WriteLine(Process.GetCurrentProcess().Threads.Count);Thread t1 = new Thread(() =>    {        Thread.Sleep(1000);        Thread t = Thread.CurrentThread;        Console.WriteLine("Name: " + t.Name);        Console.WriteLine("ManagedThreadId: " + t.ManagedThreadId);        Console.WriteLine("State: " + t.ThreadState);        Console.WriteLine("Priority: " + t.Priority);        Console.WriteLine("IsBackground: " + t.IsBackground);        Console.WriteLine("IsThreadPoolThread: " + t.IsThreadPoolThread);    })    {        Name = "Thread1",        Priority = ThreadPriority.Highest    };t1.Start();Console.WriteLine(Process.GetCurrentProcess().Threads.Count);

We input a Lambda expression in the Thread constructor to construct a Thread task corresponding to the ThreadStart delegate (the method without the void return value. Note:

1) from the output results, we can see that there are three threads after the current program starts. After the new thread is opened, it is displayed as four threads. The thread method is sleep for one second, prevent the main thread from being too early to end after execution.

2) We can set a name for the thread to facilitate debugging. We can also set the thread priority, which will be further introduced later.

3) Row 3: the unique identifier of the managed thread. Microsoft recommends that you use the Id of the managed thread instead of the Id of the thread in the operating system to track the thread.

4) lines of code output that the current thread is neither the background thread nor the foreground thread. This is the default value. The process will wait for the foreground thread to end, and if it is a background thread, the background thread will automatically terminate after all foreground threads end. For Windows GUI applications, background threads may be used, that is, the process is still running after the program disappears from the application bar of the task manager, you can only manually terminate the process to release the memory.

5) lines of code indicate that this thread was not created by the thread pool. For details about the thread pool, see the following section.

 

Let's take a look at how to input parameters to the thread. One way is to use the method that matches the ParameterizedThreadStart delegate (the void returned value of the object parameter:

new Thread((date) => Console.WriteLine(((DateTime)date).ToString())).Start(DateTime.Now);

Because the parameters are of the object type, we have to convert them when using them. Another problem is that they do not support multiple parameters, if you want to use multiple parameters, you can only use custom objects for packaging. We can also use another method, that is, use a non-parameter method to wrap the thread method subject:

new Thread(() => Add(1, 2)).Start();
static void Add(int i, int j){    Console.WriteLine(i + j);}

The running results of the above lines of code are as follows:

 

Let's take a look at the background thread foreground thread:

new Thread(() => Console.ReadLine()) { IsBackground = false }.Start();

This is the default situation. You can see that the console has been waiting for user input. Press enter to end the program. If you set the IsBackground attribute to true, you can see that the program is completed immediately after running, there is no waiting for the end of the thread method.

We have mentioned the priority attribute of the thread before. Let's do an experiment:

bool b = true;new Thread(() =>{    while (b)    {        i++;    }}) { Priority = ThreadPriority.Highest }.Start();new Thread(() =>{    while (b)    {        j++;    }}) { Priority = ThreadPriority.Lowest }.Start();Thread.Sleep(1000);b = false;Console.WriteLine("i: {0}, j: {1}", i, j);

It is easy to start two threads. accumulate a static variable value with the highest priority and the lowest priority, and then let the main thread wait for 1 second to output the result:

 

From the results, we can see that the threads with higher priorities run a little more frequently than those with lower priority, but even the threads with the lowest priority have a great opportunity to execute.

Now let's take a look at thread interruption:

Thread t2 = new Thread(() =>    {        try        {            while (true)            {                Console.WriteLine(Thread.CurrentThread.ThreadState);                Thread.Sleep(1000);            }        }        catch (ThreadAbortException abortException)        {            Console.WriteLine("catch");            Console.WriteLine(Thread.CurrentThread.ThreadState);            Console.WriteLine((string)abortException.ExceptionState);        }    });t2.Start();Thread.Sleep(2000);t2.Abort("haha");Thread.Sleep(100);Console.WriteLine(t2.ThreadState);

In the thread method, we output the state of a thread once a second, and then the main thread breaks the thread after 2 seconds of sleep, waiting for a little time, and then obtains the state of the thread after the thread ends. You can see:

Running occurs once every second. After 2 seconds, ThreadAbortException is penalized due to thread interruption and enters the catch Block. At this time, the thread status is AbortRequested, which can also receive the status information passed in when we interrupt the thread, the final thread status is Stopped.

Now let's take a look at the thread Join, which is used to block the completion of Join threads such as call threads, or to pass in a time to block a certain time:

Thread t3 = new Thread(() =>    {        for (int k = 0; k < 10; k++)        {            Thread.Sleep(100);            Console.Write("X");        }        Console.WriteLine();    });Thread t4 = new Thread(() =>{    for (int k = 0; k < 10; k++)    {        Thread.Sleep(100);        Console.Write("Y");    }    Console.WriteLine();});t3.Start();t3.Join(TimeSpan.FromMilliseconds(500));t4.Start();Console.WriteLine();

We can see that after t3 is started, the main thread is blocked for 500 milliseconds. In this case, t3 should have output a number of X, then we start t4, and then 500 milliseconds, t3 and t4 alternate output X and Y. the last 500 milliseconds since t3 has ended, only Y is output:

 

Finally, let's look at an interesting question:

We set a static field:

static int threadstaticvalue;

Create two threads to accumulate this value cyclically:

new Thread(() =>{    for (int l = 0; l < 100000; l++)    {        threadstaticvalue++;    }    Console.WriteLine("from {0}: {1}", Thread.CurrentThread.Name, threadstaticvalue);}) { Name = "1" }.Start();new Thread(() =>{    for (int m = 0; m < 200000; m++)    {        threadstaticvalue++;    }    Console.WriteLine("from {0}: {1}", Thread.CurrentThread.Name, threadstaticvalue);}) { Name = "2" }.Start();

The output result is as follows:

Although we have specified two threads to accumulate values for 0.1 million times and 0.2 million times respectively in the code, we can see that the output results are varied! This is because both threads have accessed the shared static fields, and the access may be mistakenly synchronized. In fact, adding a ThreadStatic feature to a static field can solve the problem:

[ThreadStatic]static int threadstaticvalue;

Thread Synchronization is a big topic. We will discuss it next time.

Author: lovecindywang: The copyright of this article is shared by the author and the blog. You are welcome to reprint it. However, you must keep this statement without the author's consent and provide a connection to the original text on the article page, otherwise, you are entitled to pursue legal liability.

Related Article

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.