.NET并行(多核)编程系列之七 共享数据问题和解决概述

  之前的文章介绍了了并行编程的一些基础的知识,从本篇开始,将会讲述并行编程中实际遇到一些问题,接下来的几篇将会讲述数据共享问题。

  本篇的议题如下:

  1.数据竞争

  2.解决方案提出

  3.顺序的执行解决方案

  4.数据不变解决方案

  在开始之前,首先,我们来看一个很有趣的例子:

class BankAccount   
{
public int Balance
{
get;
set;
}
}
class App
{
static void Main(string[] args)
{
// create the bank account instance
BankAccount account = new BankAccount();
// create an array of tasks
Task[] tasks = new Task[10];
for (int i = 0; i < 10; i++)
{
// create a new task
tasks[i] = new Task(() =>
{
// enter a loop for 1000 balance updates
for (int j = 0; j < 1000; 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();
}
}

NET技术.NET并行(多核)编程系列之七 共享数据问题和解决概述,转载需保留来源!

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。