Lab 07 - Programming threads
Lab 07 - Programming threads
BESE – 14AB
Submitted By:
Name CMS ID
Implement a simple program using for loop to calculate the sum of first 100 million positive
integers (i.e., 100,000,000) elements in an array.
CODE :
#include <stdio.h>
int main() {
long long sum = 0;
int n = 100000000; // 100 million integers
OUTPUT:
Convert the above code into multi-threaded program using pthreads library, which runs 4 threads
in parallel.
CODE :
#include <stdio.h>
#include <pthread.h>
#define N 100000000
#define THREADS 4
typedef struct {
long long start;
long long end;
long long sum;
} ThreadData;
// Function that each thread will run to compute the sum of its
range
void* compute_sum(void* arg) {
ThreadData* data = (ThreadData*) arg;
data->sum = 0;
return NULL;
}
int main() {
pthread_t threads[THREADS];
ThreadData thread_data[THREADS];
long long total_sum = 0;
// Create threads
for (int i = 0; i < THREADS; i++) {
thread_data[i].start = i * range_size + 1;
OUTPUT:
Run the above code several time to verify that the threads runs concurrently and threads
execution varies in each run.
The code is modified to include debug print statements inside the thread function to observe
when each thread starts and ends. This will help visualize the concurrent execution.
CODE:
#include <stdio.h>
#include <pthread.h>
#define N 100000000
#define THREADS 4
typedef struct {
long long start;
long long end;
long long sum;
int thread_id;
} ThreadData;
// Function that each thread will run to compute the sum of its range
void* compute_sum(void* arg) {
ThreadData* data = (ThreadData*) arg;
data->sum = 0;
return NULL;
}
int main() {
pthread_t threads[THREADS];
ThreadData thread_data[THREADS];
long long total_sum = 0;
OUTPUT:
Use the code in task 1 and 2 to print the time each program takes to execute. Which program
runs faster and why?
To measure the time taken for execution of each code, we add new statements that measure the
start and end times and finally the time interval (end-start).
Task 1:
CODE:
#include <stdio.h>
#include <time.h>
int main() {
long long sum = 0;
int n = 100000000; // 100 million integers
return 0;
}
OUTPUT:
CODE:
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#define N 100000000
#define THREADS 4
typedef struct {
long long start;
long long end;
long long sum;
} ThreadData;
// Function that each thread will run to compute the sum of its range
void* compute_sum(void* arg) {
ThreadData* data = (ThreadData*) arg;
data->sum = 0;
return NULL;
}
int main() {
pthread_t threads[THREADS];
ThreadData thread_data[THREADS];
long long total_sum = 0;
// Create threads
for (int i = 0; i < THREADS; i++) {
thread_data[i].start = i * range_size + 1;
thread_data[i].end = (i == THREADS - 1) ? N : (i + 1) *
range_size;
OUTPUT: