1.4.3.1 parallel immutable Program

Source: Internet
Author: User

1.4.3.1 parallel immutable Program

 

First, let's take a look at listing 1.8, which is two pieces of game code written in function mode. In the first section, the second row uses the result of the first row (the status of the monster after the movement ). Since the immutable class is used, it does not introduce a parallel mechanism to any space.

The two lines of the second code are independent. As we have just said, functional programming allows independent programs to run in parallel. Now, we find that immutability is a good way to find out which programs are independent. Even if we do not know any details, we can see the changes that can be brought about by two operations in parallel. The changes to the source code are the smallest:

 

VaR hitmonster = task. Factory. startnew () =>

Monster. hitbyshooting (GUNSHOT ));

VaR hitplayer = task. Factory. startnew () =>

Player. hitbyshooting (GUNSHOT ));

 

The only thing we have to do is encapsulate this computing task. This is a type in the parallel extensions Library (which will be discussed in detail in chapter 14th) writing less Code is not the only benefit. More importantly, it ensures the correctness of the Code. If you make similar changes in the imperative program, you must carefully check the hitbyshooting method (and all other methods it calls), locate all the locations that access the variable state, and lock it to protect the code, read and Write the shared status. In functional programming, everything is immutable, so we don't need to add any locks.

This example uses task-based parallelism, which is a low-level form. In chapter 14th, we will discuss three methods. In the next section, another method will be discussed, benefiting from the Declarative Programming style.

 

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.