Thread and Sync in C # (Threads and synchronizations in C #)

Source: Internet
Author: User
Tags define implement reset sleep thread

Don ' t believe everything they ' ve told you. Threads in C # are actually pretty easy.

Don't trust all the things that people tell you. In fact, the threads in C # are very simple.

A thread is a encapsulation of the "flow of" program. You might being used to writing single-threaded Programs-that is, programs this only execute one path through their code "a T a time ". If you have more than one thread, then code paths run "simultaneously".

A thread is the encapsulation of a control flow in a program. You may have been used to writing single-threaded programs, that is, the program executes only one path at a time in their code. If you get a few more threads, the code may run more "synchronized".

Why are some phrases above in quotes? In a typical process in the which multiple threads exist, zero or more threads may actually is running at any one time. However on a machine so got n CPU ' only one thread (actually) can run at any given time on each CPU, because each Threa D is a code path, and each CPU can be run one code-action at a time. The appearance of running many more than n "simultaneously" are done by sharing the CPUs among.

In a typical process with multithreading, 0 or more threads are running at the same time. However, on a machine with n CPUs, a thread can run on only one CPU at a given time, because each thread is a piece of code, and each CPU can only run a piece of code at one time. And it looks like N. Simultaneous completion is the effect of shared CPU time slices between threads.

In this example we create another thread, we'll try to implement a way to demonstrate the multithreaded way of work ing between the two threads we have, and at the end, we'll sync the two threads (the main and the new one) for letting T He new thread ' wait ' for a message before continuing.

In this example, we'll create another thread, we'll use two threads to demonstrate how multithreading works, and finally, we'll implement two threads (the main thread and the new thread) to synchronize and wait for the message before the new thread works.

To create a thread we need to add the System.Threading namespace. After which we need to understand this a thread has GOT to have a, the to. The start point is a function, which should being in the same call or in a different one.

We must introduce the System.Threading namespace before creating the thread. Then what I need to know is that threads have to establish a starting point for the control process. The starting point is a function that can make one of the same calls or other.

Here you can have a function in the same class this is defined as the "Start point."

Here you can see the start function defined in the same class.

Using System;

Using System.Threading;

Namespace Threadingtester

{

Class ThreadClass

{

public static void Trmain ()

{

for (int x=0;x < 10;x++)

{

Thread.Sleep (1000);

Console.WriteLine (x);

}

}

static void Main (string[] args)

{

Thread Thrd1=new Thread (new ThreadStart (Trmain));

Thrd1. Start ();

for (int x=0;x < 10;x++)

{

Thread.Sleep (900);

Console.WriteLine ("Main:" + x);

}

}

}

}

Thread.Sleep (n) method puts the *this* thread into a sleep for n milliseconds. You can have a example, that's in main we define a new thread, which it start point is the function trmain (), we Then Invoke the Start () method to begin the execution.


The Thread.Sleep (n) method places the "This" thread in the N-millisecond hibernation state. You can look at this example, in the main function we define a new thread, where its starting point is the function Trmain (), and we then include the start () method to execute.

If You run this example, you'll know the context switch between the threads (the process of letting a thread run in The CPU and then switching to another thread) lets the threads run almost together, I have placed the main thread to Slee P-milliseconds less than the new thread in order to the which one thread runs "faster".

If you run this example, you will understand the switch between threads (let the CPU move from one thread to another) so that the thread runs almost simultaneously, in order to see which thread is running faster I set the primary thread 100 milliseconds less than the new thread.

Now, a thread could is assigned with a name, before starting the thread we could:

Now, before starting the thread, give the thread a first name:

Thread Thrd1=new Thread (new ThreadStart (Trmain));

Thrd1. Name= "Thread1";

Thrd1. Start ();

In the thread itself, we can take the name into usage by:

Thread tr = thread.currentthread;

Console.WriteLine (tr. Name);

After we made that, imagine so we don ' t want the new thread to run to the "end immediately" when we start it, say we want To start the new thread, let it run, at a certain point the new thread would pause and'll wait for a n Thread (or from another thread).

After completing the above program, imagine that we do not want to start a new thread at the beginning of the end, that is, we opened a new thread, let it run, at a certain point in time, the new thread paused and wait for the message from the main thread (or other threads).


We can do so by defining:

We can define this:

public static ManualResetEvent MRE = new ManualResetEvent (false);

The ManualResetEvent is being created with false as start state, this class is being used to signal another thread, and to Wait for one or more threads. Note This all threads should have access to, "class in" to signal or listen on the same one.

ManualResetEvent is established by using false as the initial state of start, which notifies another thread to wait for one or more threads. Note that all other threads can access that class in order to notify or monitor the same thread.

The waiting thread should:

Wait for the thread to write this:

MRe. WaitOne ();

This would cause the waiting thread to pause indefinitely and wait for the class to be signaled.

This causes the waiting thread to block indefinitely and wait for the class to be notified.

The signaling thread should:

The signal thread should be like this:

MRe. Set ();

That would cause the class to be signaled as true, and the waiting thread would stop waiting. After signaling a event we can reset it to the base state by:

The class is notified, the value becomes true, and the waiting thread stops waiting. After the notification event occurs, we can use the following statement to place the thread in the base state:

MRe. Reset ();

Now lets implement the all, a single application:

Now let's do it in the program:

Using System;

Using System.Threading;

Namespace Threadingtester

{

Class ThreadClass

{

public static ManualResetEvent Mre=new ManualResetEvent (false);

public static void Trmain ()

{

Thread tr = thread.currentthread;

Console.WriteLine ("Thread:waiting for an event");

MRe. WaitOne ();

Console.WriteLine ("Thread:got an event");

for (int x=0;x < 10;x++)

{

Thread.Sleep (1000);

Console.WriteLine (tr. Name + ":" + x);

}

}

static void Main (string[] args)

{

Thread Thrd1=new Thread (new ThreadStart (Trmain));

Thrd1. Name= "Thread1";

Thrd1. Start ();

for (int x=0;x < 10;x++)

{

Thread.Sleep (900);

Console.WriteLine ("Main:" + x);

if (5==x) MRE. Set ();

}

while (Thrd1. IsAlive)

{

Thread.Sleep (1000);

Console.WriteLine ("Main:waiting for thread to stop ...");

}

}

}

}



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.