|
之前的文章介紹了了并行編程的一些基礎(chǔ)的知識(shí),從本篇開(kāi)始,將會(huì)講述并行編程中實(shí)際遇到一些問(wèn)題,接下來(lái)的幾篇將會(huì)講述數(shù)據(jù)共享問(wèn)題。
本篇的議題如下:
1.數(shù)據(jù)競(jìng)爭(zhēng)
2.解決方案提出
3.順序的執(zhí)行解決方案
4.數(shù)據(jù)不變解決方案
在開(kāi)始之前,首先,我們來(lái)看一個(gè)很有趣的例子:
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技術(shù):.NET并行(多核)編程系列之七 共享數(shù)據(jù)問(wèn)題和解決概述,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。