Asynchronous programming (asynchronous programming)

Source: Internet
Author: User
Tags readfile sprintf advantage

Asynchronous programming (asynchronous programming)

Asynchronous programming is somewhat different from the other parallel programming forms we have seen, and other topics discussed can be run in parallel with a large number of threads that can take full advantage of the processors available in the system, while in asynchronous programming we need to avoid blocking threads, and in the first section of this chapter we "thread, memory, lock, and block" The concept of blocking threads has already been understood. A blocked thread is a thread that cannot work because it needs to wait for other tasks to finish, and the usual task for a thread to wait is the input and output that the operating system executes, but sometimes it may be waiting for a lock, and therefore a critical section. Threads are relatively expensive resources, each of which allocates a stack of 1 megabytes (stacks), and other related consumption that the operating system kernel generates to manage a large number of threads. In the performance-oriented code, it is critical to keep the number of blocked threads at a lower level, in theory, as long as there are as many processors as possible, there will be no blocked threads.

Attention

To get an overview of what you can achieve with these methods, take a look at Amanda Laucher's speech in Lang.net in 2009, explaining how to use F # workflows to parallelize C # programs. and achieved some impressive results: www.langnetsymposium.com/2009/speakers.aspx.

In this section, we will learn how to use the. NET Framework's asynchronous Programming model (asynchronous programming model) to avoid thread blocking during input and output. The asynchronous programming model means that a pair of begin/end methods, such as Beginread/endread, are used on the class of the stream, typically, this pair of methods performs some kind of input-output task, such as reading a file. This programming method has a bad reputation because it needs to find a good way to keep state between Begin/end calls. In this section we discuss the programming model directly, instead, look at a feature of F #, an asynchronous workflow (asynchronous workflows), to see how it can be used to avoid work related to using asynchronous programming models in other. NET languages. For a more detailed understanding of the asynchronous programming model and the difficulty of using it, refer to Jeffrey Richter on MSDN, asynchronous Device Operations (http://msdn.microsoft.com/en-us /magazine/cc163415.aspx).

Asynchronous workflows are not dedicated to the asynchronous programming model of. NET. In the next section, "Messaging," we'll learn how to use these workflows to coordinate a number of different tasks with F # mailboxes (mailboxes), which can wait for the task to complete without blocking the thread.

The first step in understanding an asynchronous workflow in F # is to understand its syntax. Create an asynchronous workflow, using the unary syntax (monadic syntax), similar to the sequence expression we have seen in chapter III; The basic syntax uses the keyword async, which is enclosed in curly braces, in the workflow expression: Async {...}. A simple workflow program uses workflows like this:

Open System.IO

A function to read a text fileasynchronusly

Let ReadFile file =

async{let! stream = File.asyncopentext (File)

let! FileContents = stream. Asyncreadtoend ()

Return filecontents}

Create an instance of the workflow

Let Readfileworkflow = ReadFile "Mytextfile.txt"

Invoke the workflow and get the contents

Let filecontents = Async.runsynchronouslyreadfileworkflow

To compile this program, you need to refer to FSharp.PowerPack.dll. The ReadFile function in the program creates a work, asynchronously reads the file, and then returns the contents of the file; Next, create an instance of the workflow Readfileworkflow; Finally, run the workflow to get the contents of the file. It is important to understand that only calling the ReadFile function does not really read the file; instead, it reports a new instance of the workflow, and then runs the workflow to perform the task of reading the file; The async.runsynchronously function is really responsible for running the workflow. A workflow instance is a small data structure that is somewhat like a small program that can explain some of the work to be done.

The most important thing to follow in this example is the exclamation mark (let!) behind let, which is usually read as let bang. Workflow/unary syntax can be let! Give a different meaning. In an asynchronous workflow, it represents the asynchronous operation that will occur, the workflow stops running during an asynchronous operation, a callback function is inserted in the thread pool, and is called when the asynchronous operation is completed, which can occur on different threads if the threads making the original call are not idle, and the original thread is freed after the asynchronous invocation. can continue other work.

You may have noticed that let! is used in some specialized methods with async prefixes, in FSharp.PowerPack.dll, these functions are defined as type amplification (types augmentations), which are associated with C # extension methods (extension

Methods) equivalent, these methods handle calls to the Begin/end method pair. If there is no existing Async method, we create it ourselves very simply, using the Async.primitive function and the Begin/end method.

The simple steps may look like this:

The first step: the main program thread initiates the process of opening the file stream, inserting a callback function into the thread pool, which is used when the operation is complete, and the threads are now free to continue doing other work;

Second step: When the file stream is already open, thread pool threads (A thread pool threaded) are activated to begin reading the contents of the file, inserting a callback function into the thread pools, which is used when the operation is complete. Because it is a thread pool, it will be returned to the thread pool;

Step three: When the read file has been completed, thread pool threads are activated, the text data read from the file is returned and returned to the thread pool;

Fourth step: Because we have used sync. runsynchronously function, the main program thread waits for the result of the workflow and receives the contents of the file.

In this simple example, you may also find a flaw that does not block the main program thread waiting for input and output, but because we wait for the asynchronous workflow to complete, it blocks the main program thread until the input and output is complete. In another way, in its own [thread?] Running an asynchronous workflow on and waiting for a result, there is no or almost no advantage. However, running several workflows in parallel is fairly straightforward, and running several workflows at the same time has a distinct advantage because the original thread is not blocked after it starts the first asynchronous task-that is, it is idle and can continue to run other asynchronous tasks.

To illustrate this is also very simple, we have the original example for a little change, not to read a file, but read three of files. Compare this with the synchronous version of the program to help find the difference between them. Let's take a look at the synchronous version:

Open System

Open System.IO

Open System.Threading

Let print s =

Lettid = Thread.CurrentThread.ManagedThreadId

Console.WriteLine (sprintf "Thread%i:%s" Tid s)

Let Readfilesync file =

Print (sprintf "Beginning file%s" file)

Letstream = File.OpenText (File)

Letfilecontents = stream. ReadToEnd ()

Print (sprintf "ending file%s" file)

FileContents

Invoke the workflow and get the contents

Let filescontents =

[|readfilesync "Text1.txt";

Readfilesync "Text2.txt";

Readfilesync "Text3.txt"; |]

This program is quite simple, and there are some debugging code that shows the beginning and end of the processing file. Now look at the asynchronous version:

Open System

Open System.IO

Open System.Threading

Let print s =

Lettid = Thread.CurrentThread.ManagedThreadId

Console.WriteLine (sprintf "Thread%i:%s" Tid s)

A function to read a text fileasynchronusly

Let Readfileasync file =

async{do print (sprintf "Beginning file%s" file)

let! stream = File.asyncopentext (File)

let! FileContents = stream. Asyncreadtoend ()

Do print (sprintf "ending file%s" file)

Return filecontents}

Let filescontents =

async.runsynchronously

(async.parallel[readfileasync "Text1.txt";

Readfileasync "Text2.txt";

Readfileasync "Text3.txt"; ])

In addition, this version contains some debugging code, so you can see how the program works. The biggest change is that the Async.Parallel function is now used to combine several workflows into a single workflow. This way, when the first thread finishes processing the first asynchronous call, it is idle and can continue processing other workflows. Take a look at the results of the following two programs:

Synchronization results:

Thread 1:beginning File Text1.txt

Thread 1:ending File Text1.txt

Thread 1:beginning File Text2.txt

Thread 1:ending File Text2.txt

Thread 1:beginning File Text3.txt

Thread 1:ending File Text3.txt

Asynchronous results:

Thread 3:beginning File Text1.txt

Thread 4:beginning File Text2.txt

Thread 3:beginning File Text3.txt

Thread 4:ending File Text2.txt

Thread 4:ending File Text1.txt

Thread 4:ending File Text3.txt

The results of the two groups are completely different. For the synchronization result, each Beginning file is followed by a ending file and appears in the same thread; In the second case, all instances of the beginningfile occur simultaneously and in two different threads, because each thread completes the asynchronous operation. It's free. You can start another operation on the secondary. Once the input and output is complete, the ending file occurs.

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.