Untitled

 avatar
unknown
plain_text
2 years ago
1.8 kB
5
Indexable
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

int num1, num2, result;
pthread_mutex_t mutex;

void *thread1(void *arg) {
    printf("Thread 1: Enter two numbers: ");
    scanf("%d %d", &num1, &num2);
    pthread_exit(NULL);
}

void *thread2(void *arg) {
    int choice;
    printf("Thread 2: Press 1 for multiplication or 2 for division: ");
    scanf("%d", &choice);

    pthread_mutex_lock(&mutex);
    if (choice == 1) {
        result = num1 * num2;
    } else if (choice == 2 && num2 != 0) {
        result = num1 / num2;
    } else {
        printf("Invalid choice or division by zero!\n");
        exit(EXIT_FAILURE);
    }
    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

void *thread3(void *arg) {
    pthread_mutex_lock(&mutex);
    printf("Thread 3: Result is %d\n", result);
    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

int main() {
    pthread_t tid1, tid2, tid3;
    int ret;

    // Initialize the mutex
    pthread_mutex_init(&mutex, NULL);

    // Create Thread 1
    ret = pthread_create(&tid1, NULL, thread1, NULL);
    if (ret) {
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }

    // Create Thread 2
    ret = pthread_create(&tid2, NULL, thread2, NULL);
    if (ret) {
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }

    // Create Thread 3
    ret = pthread_create(&tid3, NULL, thread3, NULL);
    if (ret) {
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }

    // Wait for all threads to finish
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);

    printf("Operations have been done! Congrats\n");

    // Destroy the mutex
    pthread_mutex_destroy(&mutex);

    return 0;
}
Editor is loading...
Leave a Comment