ভূমিকা
পিথ্রেড (POSIX Threads) লাইব্রেরি ব্যবহার করে দুটি থ্রেড তৈরি করা হয়—একটি জোড় সংখ্যা প্রিন্ট করে, অন্যটি বিজোড় সংখ্যা। মিউটেক্স (mutex) এবং কন্ডিশন ভেরিয়েবল (condition variable) ব্যবহার করে সিঙ্ক্রোনাইজেশন করা হয় যাতে ১ থেকে ১০ পর্যন্ত সংখ্যা ক্রমাগত প্রিন্ট হয়।
থ্রেড কী?
থ্রেড হলো একটি লাইটওয়েট প্রসেস যা প্রোগ্রামের ভিতরে চলে। C-তে বিল্ট-ইন মাল্টিথ্রেডিং নেই, POSIX Threads (pthread) স্ট্যান্ডার্ড ব্যবহার করা হয়।
এলগরিদম
গ্লোবাল: MAX=10, count=1
pthread_mutex_t thr, pthread_cond_t cond
void* even(void* arg)
শুরু
যতক্ষণ count < MAX:
pthread_mutex_lock(&thr)
যতক্ষণ count % 2 != 0: pthread_cond_wait(&cond, &thr)
count++ প্রিন্ট করুন
pthread_mutex_unlock(&thr)
pthread_cond_signal(&cond)
pthread_exit(0)
শেষ
void* odd(void* arg)
শুরু
যতক্ষণ count < MAX:
pthread_mutex_lock(&thr)
যতক্ষণ count % 2 != 1: pthread_cond_wait(&cond, &thr)
count++ প্রিন্ট করুন
pthread_mutex_unlock(&thr)
pthread_cond_signal(&cond)
pthread_exit(0)
শেষ
main()
শুরু
thread1, thread2 তৈরি
mutex ও cond ইনিশিয়ালাইজ
even ও odd থ্রেড তৈরি
join করে মেইন থ্রেডের সাথে মিলান
ডিস্ট্রয় করুন
শেষ
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, 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