কম্পিউটার টিউটোরিয়াল

থ্রেড সিনক্রোনাইজেশন ব্যবহার করে ক্রমাগত সংখ্যা প্রিন্ট করা


n সংখ্যক থ্রেড তৈরি করে সিনক্রোনাইজেশন দিয়ে ক্রমাগত সংখ্যা প্রিন্ট করা। প্রথম থ্রেড ১ প্রিন্ট করে, দ্বিতীয় ২, এভাবে চলতে থাকে। এক সময়ে একই থ্রেড প্রিন্ট করতে পারে, বাকিরা ওয়েট করে।

উদাহরণ কোড

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t* cond = NULL;
int threads;
volatile int count = 0;

void* sync_thread(void* num) {
    int thread_number = *(int*)num;
    while (1) {
        pthread_mutex_lock(&mutex);
        if (thread_number != count) {
            pthread_cond_wait(&cond[thread_number], &mutex);
        }
        printf("%d ", thread_number + 1);
        count = (count + 1) % threads;
        pthread_cond_signal(&cond[count]);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main() {
    pthread_t* thread_id;
    int* thread_arr;
    printf("\nEnter number of threads: ");
    scanf("%d", &threads);
    cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t) * threads);
    thread_id = (pthread_t*)malloc(sizeof(pthread_t) * threads);
    thread_arr = (int*)malloc(sizeof(int) * threads);
    for (int i = 0; i < threads; i++) {
        thread_arr[i] = i;
        pthread_create(&thread_id[i], NULL, sync_thread, &thread_arr[i]);
    }
    for (int i = 0; i < threads; i++)
        pthread_join(thread_id[i], NULL);
    return 0;
}

আউটপুট (৫ থ্রেডের জন্য)

1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 ... (চলতে থাকে)

  1. C প্রোগ্রামিং-এ প্রাকৃতিক সংখ্যা কলাম-ওয়াইজ (Column-wise) প্রিন্ট করা

  2. C প্রোগ্রামিং-এ নন-স্কোয়ার নম্বর (Non-Square Numbers) প্রিন্ট করা

  3. Python-এ ফিবোনাচি সিকোয়েন্স (Fibonacci Sequence) প্রিন্ট করা

  4. Python-এ লিস্ট প্রিন্ট করা