Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.7 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

int num1, num2, result;

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

// Thread 2: Operation selection thread
void* operationThread(void* arg) {
    int choice;
    printf("Thread 2: Press 1 for addition, Press 2 for subtraction: ");
    scanf("%d", &choice);

    if (choice == 1) {
        result = num1 + num2;
    } else if (choice == 2) {
        result = num1 - num2;
    } else {
        printf("Thread 2: Invalid choice\n");
    }

    pthread_exit(NULL);
}

// Thread 3: Result display thread
void* displayThread(void* arg) {
    printf("Thread 3: Result is %d\n", result);
    pthread_exit(NULL);
}

int main() {
    pid_t child_pid;

    // Create child process
    if ((child_pid = fork()) == 0) {  // Child process
        pthread_t thread1, thread2, thread3;

        // Create threads
        pthread_create(&thread1, NULL, inputThread, NULL);
        pthread_create(&thread2, NULL, operationThread, NULL);
        pthread_create(&thread3, NULL, displayThread, NULL);

        // Wait for threads to finish
        pthread_join(thread1, NULL);
        pthread_join(thread2, NULL);
        pthread_join(thread3, NULL);

        printf("Child Process: Operations have done successfully!\n");
        exit(0);
    } else if (child_pid > 0) {  // Parent process
        wait(NULL);  // Wait for child process to finish
        printf("Main Function: Child process and threads have completed.\n");
    } else {
        perror("Fork failed");
        exit(EXIT_FAILURE);
    }

    return 0;
}
Leave a Comment