0% found this document useful (0 votes)
3 views

Thread Programs Practice

The document contains two practice programs demonstrating the use of threads in C. The first program checks if a number is even or odd, while the second calculates the factorial of a given number. Both programs utilize the pthread library for thread management and include user input for number processing.

Uploaded by

sainiguharoy9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Thread Programs Practice

The document contains two practice programs demonstrating the use of threads in C. The first program checks if a number is even or odd, while the second calculates the factorial of a given number. Both programs utilize the pthread library for thread management and include user input for number processing.

Uploaded by

sainiguharoy9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

10 Practice Programs with Solutions

1. Thread to check if a number is Even or Odd

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

void* check_even_odd(void* arg) {


int num = *((int*)arg);
int* result = (int*)malloc(sizeof(int));
*result = (num % 2 == 0) ? 1 : 0;
pthread_exit((void*)result);
}

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

pthread_t t1;
int* res;

pthread_create(&t1, NULL, check_even_odd, (void*)&num);


pthread_join(t1, (void**)&res);

if (*res)
printf("%d is EVEN\n", num);
else
printf("%d is ODD\n", num);

free(res);
return 0;
}

2. Thread to calculate factorial of a number

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

void* factorial(void* arg) {


int n = *((int*)arg);
long long* fact = (long long*)malloc(sizeof(long long));
*fact = 1;
for (int i = 2; i <= n; i++) {
*fact *= i;
}
pthread_exit((void*)fact);
}

int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);

pthread_t t1;
long long* result;

pthread_create(&t1, NULL, factorial, (void*)&n);


pthread_join(t1, (void**)&result);

printf("Factorial of %d is %lld\n", n, *result);


free(result);
return 0;
}

You might also like