OS Lab 08

Pasted Nov 3, 2026, 3:42 AM2 files182 lines

Scan to open on your phone

Point a camera at the QR code - it opens this exact paste, no app needed.

https://codepastes.com/oslab08
inlab.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define NUM_THREADS 3

typedef struct {
    int thread_id;
    int start;
    int end;
} ThreadData;

int total_sum = 0;
pthread_mutex_t mutex;

void *thread_task(void *arg)
{
    ThreadData *data = (ThreadData *)arg;
    int local_sum = 0;

    for (int i = data->start; i <= data->end; i++) {
        printf("Thread %d: %d\n", data->thread_id, i);
        local_sum += i;
    }

    /* Protect the shared total from simultaneous updates. */
    pthread_mutex_lock(&mutex);
    total_sum += local_sum;
    printf("Thread %d sum: %d\n", data->thread_id, local_sum);
    pthread_mutex_unlock(&mutex);

    return NULL;
}

int main(void)
{
    pthread_t threads[NUM_THREADS];
    ThreadData data[NUM_THREADS] = {
        {1, 1, 5},
        {2, 6, 10},
        {3, 11, 15}
    };

    if (pthread_mutex_init(&mutex, NULL) != 0) {
        perror("Mutex initialization failed");
        return EXIT_FAILURE;
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        int result = pthread_create(&threads[i], NULL, thread_task, &data[i]);
        if (result != 0) {
            fprintf(stderr, "Could not create thread %d\n", i + 1);
            return EXIT_FAILURE;
        }
    }

    /* Wait until every thread has finished. */
    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    printf("Total sum: %d\n", total_sum);

    pthread_mutex_destroy(&mutex);
    return EXIT_SUCCESS;
}

4,326 chars · codepastes.com