0% found this document useful (0 votes)
2 views2 pages

Threading 2

The document presents a C program that calculates the factorial of a number using multiple threads. It defines a structure for passing data to threads, a factorial computation function, and a thread function that prints the result. The main function handles user input, creates threads for each input number, and waits for all threads to complete their execution.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Threading 2

The document presents a C program that calculates the factorial of a number using multiple threads. It defines a structure for passing data to threads, a factorial computation function, and a thread function that prints the result. The main function handles user input, creates threads for each input number, and waits for all threads to complete their execution.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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;
}

You might also like