Preface: The previous article introduced some basic knowledge of parallel programming, from this beginning, will talk about the actual encounter some problems in parallel programming, the next few will talk about data sharing problem.
The topics in this article are as follows:
Data competition
Solution proposal
Sequential Execution Solution
Data invariant Solutions
Before we begin, let's take a look at an interesting example:
class BankAccount
{
public int Balance
{
get;
Set
}
}
class App
{
static void Main (string[] args)
{
//Create the bank account ins Tance
BankAccount account = new BankAccount ();
Create an array of tasks
task[] tasks = new TASK[10];
for (int i = 0; i < i++)
{
///Create a new task
Tasks[i] = new Task (() =&G T
{
//Enter a loop for 1000 balance updates
for (int j = 0; J < 10 00; J + +)
{
//update the Balance
account. Balance = account. Balance + 1;
}
});
//Start the new task
Tasks[i]. Start ();
}
//Wait for all of the tasks to complete
Task.waitall (tasks);
Write out the counter value
Console.WriteLine ("Expected value {0}, Counter value: {1}",
10000, account. Balance);
//wait for input before exiting
Console.WriteLine ("Press ENTER to finish");
Console.ReadLine ();
}
}