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

Os 9

The document contains a C program that implements threading to calculate the sum of even and odd numbers up to a defined maximum. Two threads are created, one for calculating the even sum and another for the odd sum, with each thread printing its progress. After both threads complete their execution, the main function confirms their completion.

Uploaded by

jayaprakash9223
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)
4 views2 pages

Os 9

The document contains a C program that implements threading to calculate the sum of even and odd numbers up to a defined maximum. Two threads are created, one for calculating the even sum and another for the odd sum, with each thread printing its progress. After both threads complete their execution, the main function confirms their completion.

Uploaded by

jayaprakash9223
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

Sprno:9223

9 TO IMPLEMENT THREADING
PROGRAM:
#include <stdio.h>
#include <pthread.h>

#define MAX 10

void* even_sum(void* arg) {


int sum = 0;
for (int i = 0; i <= MAX; i++) {
if (i % 2 == 0) {
sum += i;
printf("Even Thread: adding %d, current sum = %d\n", i, sum);
}
}
printf("Even Thread: Total even sum = %d\n", sum);
return NULL;
}

void* odd_sum(void* arg) {


int sum = 0;
for (int i = 0; i <= MAX; i++) {
if (i % 2 != 0) {
sum += i;
printf("Odd Thread: adding %d, current sum = %d\n", i, sum);
}
}
printf("Odd Thread: Total odd sum = %d\n", sum);
return NULL;
}
Sprno:9223

int main() {
pthread_t thread1, thread2;

pthread_create(&thread1, NULL, even_sum, NULL);


pthread_create(&thread2, NULL, odd_sum, NULL);

pthread_join(thread1, NULL);
pthread_join(thread2, NULL);

printf("Main: Both threads have finished.\n");


return 0;
}
OUTPUT:
Even Thread: adding 0, current sum = 0

Even Thread: adding 2, current sum = 2

Odd Thread: adding 1, current sum = 1

Even Thread: adding 4, current sum = 6

Odd Thread: adding 3, current sum = 4

Even Thread: adding 6, current sum = 12

Odd Thread: adding 5, current sum = 9

Even Thread: adding 8, current sum = 20

Odd Thread: adding 7, current sum = 16

Even Thread: adding 10, current sum = 30

Odd Thread: adding 9, current sum = 25

Even Thread: Total even sum = 30

Odd Thread: Total odd sum = 25

Main: Both threads have finished.

You might also like