ได้รับเธรด โปรแกรมต้องพิมพ์เธรดตามลำดับความสำคัญตั้งแต่ 0 ถึง 10
เธรดคืออะไร?
เธรดคือกระบวนการเบาๆ ที่ทำงานภายในโปรแกรม โปรแกรมธรรมดาสามารถมีเธรดได้ n ตัว
ไม่เหมือน Java ที่รองรับมัลติเธรดมาตรฐาน POSIX Threads (Pthreads) เป็นมาตรฐานสำหรับมัลติเธรดใน C/C++ C ไม่มีการสนับสนุนมัลติเธรดในตัว แต่พึ่งพาระบบปฏิบัติการ
การทำงานในโปรแกรมของเรา
ใช้ไฟล์หัว #include
งานคือซิงโครไนซ์ n เธรดด้วยไลบรารี pthread มาตรฐานของ gcc ความคิดคือรับจำนวนเธรดและพิมพ์ 1 ในเธรดแรก 2 ในเธรดที่สอง จนถึงเธรดที่ 10 ผลลัพธ์จะมีตัวเลข 1 ถึง 10 ตามลำดับความสำคัญของเธรด
อัลกอริทึม
Start
Step 1 -> Declare global variables as int MAX=10 and count=1
Step 2 -> declare variable thr of pthread_mutex_t and cond of pthread_cond_t
Step 3 -> Declare Function void *even(void *arg)
Loop While(count < MAX)
Call pthread_mutex_lock(&thr)
Loop While(count % 2 != 0)
Call pthread_cond_wait(&cond, &thr)
End
Print count++
Call pthread_mutex_unlock(&thr)
Call pthread_cond_signal(&cond)
End
Call pthread_exit(0)
Step 4 -> Declare Function void *odd(void *arg)
Loop While(count < MAX)
Call pthread_mutex_lock(&thr)
Loop While(count % 2 != 1)
Call pthread_cond_wait(&cond, &thr)
End
Print count++
Call pthread_mutex_unlock(&thr)
Call pthread_cond_signal(&cond)
End
Set pthread_exit(0)
Step 5 -> In main()
Create pthread_t thread1 and pthread_t thread2
Call pthread_mutex_init(&thr, 0)
Call pthread_cond_init(&cond, 0)
Call pthread_create(&thread1, 0, &even, NULL)
Call pthread_create(&thread2, 0, &odd, NULL)
Call pthread_join(thread1, 0)
Call pthread_join(thread2, 0)
Call pthread_mutex_destroy(&thr)
Call pthread_cond_destroy(&cond)
Stop
ตัวอย่างโค้ด C
#include#include #include int MAX = 10; int count = 1; pthread_mutex_t thr; pthread_cond_t cond; void *even(void *arg){ while(count < MAX) { pthread_mutex_lock(&thr); while(count % 2 != 0) { pthread_cond_wait(&cond, &thr); } printf("%d ", count++); pthread_mutex_unlock(&thr); pthread_cond_signal(&cond); } pthread_exit(0); } void *odd(void *arg){ while(count < MAX) { pthread_mutex_lock(&thr); while(count % 2 != 1) { pthread_cond_wait(&cond, &thr); } printf("%d ", count++); pthread_mutex_unlock(&thr); pthread_cond_signal(&cond); } pthread_exit(0); } int main(){ pthread_t thread1; pthread_t thread2; pthread_mutex_init(&thr, 0); pthread_cond_init(&cond, 0); pthread_create(&thread1, 0, &even, NULL); pthread_create(&thread2, 0, &odd, NULL); pthread_join(thread1, 0); pthread_join(thread2, 0); pthread_mutex_destroy(&thr); pthread_cond_destroy(&cond); return 0; }
ผลลัพธ์
การรันโปรแกรมจะได้ผลลัพธ์ดังนี้:
1 2 3 4 5 6 7 8 9 10