ด้วยเธรด โปรแกรมจะต้องพิมพ์เธรดตามลำดับความสำคัญตั้งแต่ 0 ถึง 10
กระทู้คืออะไร
เธรดเป็นกระบวนการที่มีน้ำหนักเบาซึ่งทำงานภายในโปรแกรม โปรแกรมอย่างง่ายสามารถมีได้ n จำนวนเธรด
มาตรฐานภาษาไม่รองรับจาวา มัลติเธรดดิ้ง POSIX Threads (Pthreads) เป็นมาตรฐานที่ใช้ในการทำมัลติเธรดใน C/C++ C ไม่มีการสนับสนุนในตัวสำหรับแอปพลิเคชันแบบมัลติเธรด แต่อาศัยระบบปฏิบัติการทั้งหมดเพื่อให้คุณลักษณะนี้แทน
มันทำงานอย่างไรในโปรแกรมของเรา
ในการใช้ฟังก์ชันเธรด เราใช้ไฟล์ส่วนหัว #include ไฟล์ส่วนหัวนี้จะรวมฟังก์ชันทั้งหมดที่เกี่ยวข้องกับเธรดในโปรแกรมของเรา เช่น pthread_create() เป็นต้น
ตอนนี้งานคือการซิงโครไนซ์จำนวนเธรด n โดยใช้ไลบรารีมาตรฐาน pthread ที่มีอยู่กับคอมไพเลอร์ gcc แนวคิดคือนับจำนวนเธรดและพิมพ์ 1 ในเธรดแรก พิมพ์ 2 ในเธรดที่สอง พิมพ์ 3 ในเธรดที่สามจนถึงเธรดที่ 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
ตัวอย่าง
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
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