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

Multi Threading

The document presents a C program that calculates the sum of 100,000 integers using four threads for parallel processing. Each thread computes the sum of a specific range of integers, and proper error handling is implemented for thread creation. The final sum is computed by aggregating the results from all threads and displayed at the end.

Uploaded by

kaveri.nagare
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)
5 views2 pages

Multi Threading

The document presents a C program that calculates the sum of 100,000 integers using four threads for parallel processing. Each thread computes the sum of a specific range of integers, and proper error handling is implemented for thread creation. The final sum is computed by aggregating the results from all threads and displayed at the end.

Uploaded by

kaveri.nagare
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

Title:= addition of 1 Lakh integer numbers - with proper error handling

UID:=UIT2025005
______________________________________________________________________
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

typedef struct {
int start;
int end;
long sum;
} ThreadData;

void* CalSum(void* arg)


{
ThreadData* data = (ThreadData*)arg;
data->sum = 0;

for(int i = data->start; i <= data->end; i++)


{
data->sum += i;
}
printf("Thread (%d to %d) Sum = %ld\n",
data->start, data->end, data->sum);

pthread_exit(NULL);
}
int main()
{
pthread_t t1, t2, t3, t4;
ThreadData d1 = {1, 25000, 0};
ThreadData d2 = {25001, 50000, 0};
ThreadData d3 = {50001, 75000, 0};
ThreadData d4 = {75001, 100000, 0};

if (pthread_create(&t1, NULL, CalSum, &d1) != 0)


{
perror("Thread 1 creation failed");
exit(1);
}
if (pthread_create(&t2, NULL, CalSum, &d2) != 0)
{
perror("Thread 2 creation failed");
exit(1);
}

if (pthread_create(&t3, NULL, CalSum, &d3) != 0)


{
perror("Thread 3 creation failed");
exit(1);
}

if (pthread_create(&t4, NULL, CalSum, &d4) != 0)


{
perror("Thread 4 creation failed");
exit(1);
}
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_join(t4, NULL);
long total = [Link] + [Link] + [Link] + [Link];
printf("\nFinal Sum = %ld\n", total);

return 0;
}
OUTPUT:=

You might also like