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.