using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<Person> people = new List<Person>();
people.Add(new Person("kim sam soon", 12));
people.Add(new Person("park chul soon", 23));
people.Add(new Person("obama", 65));
people.Add(new Person("lee so ryong", 11));
people.Add(new Person("choo shin soo", 27));
people.Add(new Person("buffet", 80));
var enumerator = (IEnumerator<Person>)people.GetEnumerator();
while(enumerator.MoveNext() != false){
var e = enumerator.Current;
Console.WriteLine(e);
}
Console.WriteLine("=====================");
ParallelSort(people);
//ThreadSort(people);
//GeneralSort(people);
}
private static void GeneralSort(List<Person> people)
{
List<Person> resultPeople = new List<Person>();
foreach (Person person in people)
{
if (person.Age >= 20)
resultPeople.Add(person);
}
resultPeople.Sort((p1, p2) => p1.Age.CompareTo(p2.Age));
foreach (var item in resultPeople)
{
Console.WriteLine(item);
}
}
private static void ThreadSort(List<Person> people)
{
var resultPeople = new List<Person>();
int partitionsCount = Environment.ProcessorCount;
int remainingCount = partitionsCount;
using (var enumerator = (IEnumerator<Person>)people.GetEnumerator())
{
using (var done = new System.Threading.ManualResetEvent(false))
{
for (int i = 0; i < partitionsCount; i++)
{
System.Threading.ThreadPool.QueueUserWorkItem(delegate
{
var partialResults = new List<Person>();
while(true)
{
Person baby;
lock(enumerator)
{
if( enumerator.MoveNext() == false )
break;
baby = enumerator.Current;
}
if (baby.Age >= 20)
partialResults.Add(baby);
}
lock (resultPeople) resultPeople.AddRange(partialResults);
if (System.Threading.Interlocked.Decrement(ref remainingCount) == 0)
done.Set();
});
}
done.WaitOne();
resultPeople.Sort( (p1, p2) => p1.Age.CompareTo(p2.Age) );
}
}
foreach (var item in resultPeople)
{
Console.WriteLine(item);
}
}
private static void ParallelSort(List<Person> people)
{
var resultPeople = from person in people.AsParallel()
where person.Age >= 20
orderby person.Age ascending
select person;
foreach (var item in resultPeople)
{
Console.WriteLine(item);
}
}
}
}
'C#, .NET' 카테고리의 다른 글
C# Enumerator (0) | 2012.08.23 |
---|---|
C#에서 프로세서 개수 알아내기 (0) | 2012.08.23 |
C# 및 SQL 강좌 (0) | 2012.08.22 |