Thread คือ ?

2009-09-30 / Programming / 2 Comments

ABStart

Thread คืออะไร ผมก็ไม่รู้ จำได้ลาง ๆ ตอนเรียนว่า Thread เป็นการทำงานแบบขนานใน Process (เรียก Mutithread) โดย Thread นั้นสามารถใช้ resource ร่วมกันได้ (Data, File, …)

เมือก่อนตอนใน 1 process จะทำงานแค่ 1 thread เท่านั้น
ลองนึกภาพ code นี้ดู

int main()
{
char inChar;
inChar = getch();
printf(“Welcome\n”);
}

จาก code ดังกล่าวเป็นการทำงานแบบ Thread เดียว คือโปรแกรมต้องรับอินพุตจาก Keyboard ก่อนถึงจะแสดงคำว่า Welcome ได้
หรือลองนึกภาพห้องเรียนที่กำลังจะเลิกเรียน แล้วคุณครูให้เด็กชาย A มาเขียนสูตรคูณแม่ 2 กับแม่ 3 ลงบนกระดาน โดยความสามารถของเด็กชาย A นั้นสามารถเขียนสูตรคูณได้ 1 นาที / 1 บรรทัด ดังนั้นเด็กชาย A ต้องใช้เวลา 24 นาทีจึงเขียนเสร็จ(ตัวอย่างโค๊ดที่ 1) (แบบนี้เรียก thread เดียว) ดังนั้นคุณครูเลยให้เด็กชาย B มาช่วยเขียนโดยให้เด็กชาย A เขียนแม่ 2 แล้วให้เด็กชาย B เขียนแม่ 3 นึกภาพกระดานดำเป็นเป็นสองฝั่ง แล้วเด็กชาย A และ เด็กชาย B ช่วยกันเขียน(ตัวอย่างโค๊ดที่ 2) คนละฝั่ง (แบบนี้เรียก Mutithread)
ลองดูจาก Code ข้างล่างและผลการรันโปรแกรมครับ

ตัวอย่างโค๊ดที่ 1

static void Main(string[] args)
{
for (int j = 2; j < 4; j++)
{
for (int i = 0; i < 13; i++)
{
Console.WriteLine(“A : {0} x {1} = {2}”, j, i,i * j);
}
}
}

Aonly

ตัวอย่างโค๊ดที่ 2

static Thread studentA;
static Thread studentB;

static void Main(string[] args)
{
studentA = new Thread(new ThreadStart(studentAWrite));
studentB = new Thread(new ThreadStart(studentBWrite));

studentA.Start();
studentB.Start();
}

static void studentAWrite()
{
for (int i = 0; i < 13; i++)
{
Console.WriteLine(“A : 2 x {0} = {1}”, i, i * 2);
Thread.Sleep(10);
}
if (studentA.IsAlive == true)
{
studentA.Abort();
}
}
static void studentBWrite()
{
for (int i = 0; i < 13; i++)
{
Console.WriteLine(“B : 3 x {0} = {1}”, i, i * 3);
Thread.Sleep(10);
}
if (studentB.IsAlive == true)
{
studentB.Abort();
}
}
AandB

จาก code และผลการรันโปรแกรมจากตัวอย่างที่ 1 นั้นจะเห็นได้ว่า A ต้องเขียน สูตรคูณแม่สองให้เสร็จก่อนจึงไปทำแม่สามต่อได้

แต่ในตัวอย่างที่ 2 จะเห็นได้ว่า Thread A และ B ทำงานไปพร้อม ๆ กันในเวลาไล่เลี่ยกัน

class Program
{
static Thread studentA;
static Thread studentB;

static void Main(string[] args)
{
studentA = new Thread(new ThreadStart(studentAWrite));
studentB = new Thread(new ThreadStart(studentBWrite));

studentA.Start();
studentB.Start();
}

static void studentAWrite()
{
for (int i = 0; i < 13; i++)
{
Console.WriteLine(“A : 2 x {0} = {1}”, i, i * 2);
Thread.Sleep(10);
}
if (studentA.IsAlive == true)
{
studentA.Abort();
}
}
static void studentBWrite()
{
for (int i = 0; i < 13; i++)
{
Console.WriteLine(“B : 3 x {0} = {1}”, i, i * 3);
Thread.Sleep(10);
}
if (studentB.IsAlive == true)
{
studentB.Abort();
}
}
}

Read More