Welcome

首页 / 软件开发 / .NET编程技术 / .NET并行(多核)编程系列之七 共享数据问题和解决概述

.NET并行(多核)编程系列之七 共享数据问题和解决概述2012-02-13 博客园 小洋前言:之前的文章介绍了了并行编程的一些基础的知识,从本篇开始,将会讲述并行编程中实际遇到一些问题,接下来的几篇将会讲述数据共享问题。

本篇的议题如下:

数据竞争

解决方案提出

顺序的执行解决方案

数据不变解决方案

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

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();
}
}