0% found this document useful (0 votes)
6 views3 pages

Code - Example 2

The document contains a C program that uses multithreading to calculate the sum of integers from 1 to 10,000,000. It creates four threads, each responsible for summing a specific range of numbers, and uses a mutex to ensure thread-safe updates to the total sum. The program initializes threads, waits for their completion, and prints the final total sum.

Uploaded by

23020787
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)
6 views3 pages

Code - Example 2

The document contains a C program that uses multithreading to calculate the sum of integers from 1 to 10,000,000. It creates four threads, each responsible for summing a specific range of numbers, and uses a mutex to ensure thread-safe updates to the total sum. The program initializes threads, waits for their completion, and prints the final total sum.

Uploaded by

23020787
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

#include <stdio.

h>

#include <pthread.h>

#include <stdlib.h>

#define NUM_THREADS 4

#define RANGE 10000000

long long total_sum = 0;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *sum_range(void *arg) {

int *range = (int *)arg;

int start = range[0];

int end = range[1];

long long local_sum = 0;

for (int i = start; i <= end; i++) {

local_sum += i;

pthread_mutex_lock(&lock);

total_sum += local_sum;

pthread_mutex_unlock(&lock);

free(arg);

return NULL;

}
int main() {

pthread_t threads[NUM_THREADS];

int chunk = RANGE / NUM_THREADS;

pthread_mutex_init(&lock, NULL);

for (int i = 0; i < NUM_THREADS; i++) {

int *range = malloc(2 * sizeof(int));

range[0] = i * chunk + 1;

if ((i == NUM_THREADS – 1)

range[1] = RANGE;

else

range[1] = (i+1) * chunk;

pthread_create(&threads[i], NULL, sum_range, range);

// Wait for all threads to finish

for (int i = 0; i < NUM_THREADS; i++) {

pthread_join(threads[i], NULL);

pthread_mutex_destroy(&lock);

printf("Total sum from 1 to %d: %lld\n", RANGE, total_sum);


return 0;

You might also like