exp 5
unknown
plain_text
a month ago
1.8 kB
2
Indexable
Never
#include <pthread.h> #include <stdio.h> #include <stdint.h> #define num_threads 3 int je = 0, jo = 0, evensum = 0, oddsum = 0, evenarr[50], oddarr[50]; int sumnat = 0; // Declare sumnat as a global variable void *even(void *threadid) { int i, n; n = (int)(intptr_t)threadid; // Cast to uintptr_t and then to int for (i = 1; i <= n; i++) { // Changed condition to i <= n if (i % 2 == 0) { evenarr[je] = i; evensum += i; je++; } } pthread_exit(NULL); // Exit the thread } void *odd(void *threadid) { int i, n; n = (int)(intptr_t)threadid; // Cast to uintptr_t and then to int for (i = 1; i <= n; i++) { // Changed condition to i <= n if (i % 2 != 0) { // Fixed condition to check odd numbers oddarr[jo] = i; oddsum += i; jo++; } } pthread_exit(NULL); // Exit the thread } void *sumn(void *threadid) { int i, n; n = (int)(intptr_t)threadid; // Cast to uintptr_t and then to int for (i = 1; i <= n; i++) { // Changed condition to i <= n sumnat += i; } pthread_exit(NULL); // Exit the thread } int main() { pthread_t threads[num_threads]; int i, t; printf("Enter the n number: "); scanf("%d", &t); // Create threads pthread_create(&threads[0], NULL, even, (void *)(intptr_t)t); pthread_create(&threads[1], NULL, odd, (void *)(intptr_t)t); pthread_create(&threads[2], NULL, sumn, (void *)(intptr_t)t); // Join threads for (i = 0; i < num_threads; i++) { pthread_join(threads[i], NULL); } // Print results printf("The sum of n natural numbers is %d\n", sumnat); printf("The sum of n even numbers is %d\n", evensum); printf("The sum of n odd numbers is %d\n", oddsum); pthread_exit(NULL); }
Leave a Comment