THREADING
[Link]
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
// Structure to pass data to thread
typedef struct {
int number;
} ThreadData;
// Function to compute factorial
long long factorial(int n) {
long long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// Thread function
void* computeFactorial(void* arg) {
ThreadData* data = (ThreadData*)arg;
long long result = factorial(data->number);
printf("Thread ID: %lu\n", pthread_self());
printf("Factorial of %d = %lld\n\n", data->number, result);
return NULL;
}
int main() {
int n;
scanf("%d", &n);
pthread_t threads[n];
ThreadData data[n];
// Input numbers
for (int i = 0; i < n; i++) {
scanf("%d", &data[i].number);
}
// Create threads
for (int i = 0; i < n; i++) {
pthread_create(&threads[i], NULL, computeFactorial, &data[i]);
}
// Wait for all threads to finish
for (int i = 0; i < n; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}