Processes and Threads

Source: Internet
Author: User

Process: Represents the basic unit of resource allocation, the basic unit of dispatching operation. From a programmatic point of view, it can also be seen as an area of memory that contains some resources.

As long as the application is opened, the process is created.

Thread: is a separate instruction stream in the program. When the VS compiler enters the code, the system parses the code, underlines the missing semicolon and other grammatical errors with an underscore, which is a background thread completion.

Word documents require a thread to wait for user input, another thread to perform a background search, and a third thread to store the data written in a temporary file. A thread that is running in an application on the server waits for a client request to become a listening thread.

A process contains a resource, such as a window handle, a file system handle, or other kernel object. The virtual memory that is allocated for each process. A process consists of at least one thread.

An application starts, typically starts a process, and the process starts multiple threads.

Multithreading: (multithreading) is a technique that implements concurrent execution of multiple threads from software or hardware.

You may want to use multithreading in the following scenarios

1. The program needs to perform two or more tasks at the same time:

The program waits for an event to occur, such as user input, file manipulation, network operation, search, and so on.

Background program

Priority tasks

Related functions used by threads:

1) Introduce the thread name space

Using System.Threading

2) Create an agent

ThreadStart Proxy Object name = new ThreadStart (method name);

3) Create thread

Thread object name = new Thread (proxy object name);

4) Start thread

The name of the thread object. Start ();

Diagnostics namespace Process

Category Name Role (return value) data type
Property ProcessName Get Process Name String
Property Id Get process Unique Identifiers Int
Property Treads A collection of threads in a process Thread[]
Property MachineName Gets the computer name of the running process String
Method GetCurrentProcess Get current process Process
Static methods GetProcesses Get the processes running on the computer Process[]
Static methods Start Start process Process
Method Kill Close process void

Thread synchronization: An important aspect of using threads is to synchronize access to any variable that is accessed by multiple threads. The so-called synchronization: means that only one thread can access a variable at a time. If you cannot ensure that access to a variable is synchronous, an error occurs.

C # provides a very simple way to access variables, that is, using the C # keyword lock, as follows;

      

Lock (x) {dosomething ();}

Sync Note issues:

Do not misuse synchronization

Dead lock

Race condition

There may be only one book in a bookstore, and two salespeople sell the book at the same time, and if it's two threads, what to do. (Answer below)

Using the Lock keyword in C #, the code for the keyword scope class again is thread-safe. The lock keyword defines a tag that must be obtained when a thread enters a locked range. When a private method of an instance-level object is locked, a reference to the object that contains the method itself is used.

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading;6 usingSystem.Threading.Tasks;7 8 namespaceThread Synchronization9 {Ten      Public classBookshop One     { A          Public intnum =1; -          Public voidSale () -         { the             inttmp; -             Lock( This) -             { -TMP =num; +                 if(tmp >0) -                 { +Thread.Sleep ( +); Anum = num-1; atConsole.WriteLine ("sold a copy. "); -}Else -                 { -Console.WriteLine ("the book is gone."); -                 } -             } in         } -     } to  +     class Program -     { the         Static voidMain (string[] args) *         { $Bookshop BK =NewBookshop ();Panax NotoginsengThread T1 =NewThread (NewThreadStart (BK. Sale)); -Thread t2 =NewThread (NewThreadStart (BK. Sale)); the t1. Start (); + T2. Start (); A console.readline (); the         } +     } -}

Thread Async

For a single CPU, in a unit time (also called a time slice), only one thread can be executed, that is, the only thing to do. When the time slice of a thread is exhausted, the system suspends the thread and executes another thread within the next time, so that the cup alternates between multiple threads at the time slice (in fact, it is related to the priority of each thread and the high priority is given). Because the alternating interval is very short, it causes each thread to "simultaneously"

The illusion of work: thread async is to solve a problem similar to the previous time-consuming task that interface controls cannot use. If you create a thread to perform a time-consuming task, other tasks, such as the interface control, are assigned to another thread (often executed by the main thread). This allows the two threads to simulate the effect of "simultaneous" execution of multiple tasks by switching between threads in a short time (time slice) of the thread scheduler.

Summarize two words:

1, thread async refers to the execution of a thread, and its next thread does not have to wait for it to execute.

2, Thread synchronization means that a thread waits for the previous thread to finish executing before it starts executing the current thread.

Synchronous calls and asynchronous calls

Synchronous invocation:

The Lnvoke method of a delegate is used to make synchronous calls, or a synchronous call can be called a blocking call, which blocks the current thread and then executes the call, and then continues down after the call is complete.

asynchronous invocation

Instead of blocking the thread, the asynchronous call plugs the call into the thread pool, which the program's main thread or UI thread can continue to execute. The asynchronous invocation of a delegate is implemented by Beginlnvoke and Endlnvoke.

Asynchronous callbacks

With the callback function, the callback function is automatically invoked at the end of the call, which solves the situation where the thread is still blocked by waiting for the result.

Note: Beginlnvoke and Endlnvode must be called in pairs. Even if the return value is not required, it may cause a memory leak when Endlnvoke must be called.

Thread pool:

It takes time to create a thread pool. If you have a different small task to complete, you can create many threads beforehand and make a request when you complete these tasks. This number of threads is best added when more threads are needed and less when resources need to be freed.

You do not need to create a thread pool yourself, the system already has a ThreadPool class management thread. This class increases the number of threads in the pool as needed, until the maximum number of threads is reached. The maximum number of threads in the pool is configurable. In dual cores, the default setting is 1023 worker threads and 1000 I/O threads. You can also specify the minimum number of threads that are applied to start immediately when the thread pool is created, and the maximum number of threads available in the thread pool. If there is more work to be done, the number of threads in the thread pool is at its limit, the latest jobs are queued, and the thread must wait for the task to complete.

Processes and Threads

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.