Write a program to create a thread (T1) that computes the sum of two numbers
passed from the main process. The thread should calculate the sum and return
the result to the parent process, which will print the sum.
Test Cases
Test Case 1
Input:
num1 = -10
num2 = 15
Output:
The sum of -10 and 15 is: 5
Test Case 2
Input:
num1 = 20
num2 = 30
Output:
The sum of 20 and 30 is: 50
Assistant
Certainly! Below is a solution to the problem using C with the POSIX Threads (pthread) library. This program creates a thread to compute the sum of two numbers provided by the user. The thread calculates the sum and returns the result to the parent (main) thread, which then prints the sum.
Solution Overview
Input Handling: The main function takes two integers as input from the user.
Thread Creation: A thread (T1) is created to compute the sum of the two numbers.
Sum Calculation: The thread function computes the sum and returns the result.
Result Retrieval: The main thread waits for T1 to finish and retrieves the computed sum.
Output: The sum is printed in the specified format.
C Implementation Using POSIX Threads
c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// Structure to hold the input numbers
typedef struct {
int num1;
int num2;
} Numbers;
// Thread function to compute the sum
void* compute_sum(void* args) {
Numbers* numbers = (Numbers*)args;
int* sum = malloc(sizeof(int));
if (sum == NULL) {
fprintf(stderr, "Memory allocation failed\n");
pthread_exit(NULL);
}
*sum = numbers->num1 + numbers->num2;
pthread_exit((void*)sum);
}
int main() {
pthread_t thread;
Numbers numbers;
int rc;
void* result;
// Input
printf("Enter num1: ");
if (scanf("%d", &numbers.num1) != 1) {
fprintf(stderr, "Invalid input for num1.\n");
return EXIT_FAILURE;
}
printf("Enter num2: ");
if (scanf("%d", &numbers.num2) != 1) {
fprintf(stderr, "Invalid input for num2.\n");
return EXIT_FAILURE;
}
// Create thread
rc = pthread_create(&thread, NULL, compute_sum, (void*)&numbers);
if (rc) {
fprintf(stderr, "Error creating thread: %d\n", rc);
return EXIT_FAILURE;
}
// Wait for thread to finish and get the result
rc = pthread_join(thread, &result);
if (rc) {
fprintf(stderr, "Error joining thread: %d\n", rc);
return EXIT_FAILURE;
}
// Retrieve the sum from the thread
if (result != NULL) {
int sum = *((int*)result);
printf("The sum of %d and %d is: %d\n", numbers.num1, numbers.num2, sum);
free(result); // Free the allocated memory
} else {
fprintf(stderr, "Thread did not return a result.\n");
}
return EXIT_SUCCESS;
}
Compilation and Execution
To compile the C program using gcc, make sure to link the pthread library using the -pthread flag.
bash
gcc -pthread -o sum_program sum_program.c
Run the compiled program:
bash
./sum_program
Sample Runs
Test Case 1
Input:
code
num1 = -10
num2 = 15
Execution:
code
Enter num1: -10
Enter num2: 15
The sum of -10 and 15 is: 5
Test Case 2
Input:
code
num1 = 20
num2 = 30
Execution:
code
Enter num1: 20
Enter num2: 30
The sum of 20 and 30 is: 50
Explanation
Data Structure (Numbers): A simple structure to pass both numbers to the thread function.
Thread Function (compute_sum):
Receives a pointer to Numbers.
Allocates memory to store the sum.
Computes the sum and stores it in the allocated memory.
Exits the thread, returning the pointer to the sum.
Main Function:
Reads two integers from the user.
Creates a thread, passing the Numbers structure.
Waits for the thread to finish using pthread_join and retrieves the sum.
Prints the result and frees the allocated memory.
Note: Dynamic memory allocation (malloc) is used in the thread function to safely return the sum to the main thread. It's essential to free this memory in the main thread to avoid memory leaks.
Alternative Implementation in Python
For comparison, here's how you might implement the same functionality using Python's threading module.
python
import threading
# Function to compute the sum
def compute_sum(num1, num2, result):
result.append(num1 + num2)
def main():
try:
num1 = int(input("Enter num1: "))
except ValueError:
print("Invalid input for num1.")
return
try:
num2 = int(input("Enter num2: "))
except ValueError:
print("Invalid input for num2.")
return
result = []
thread = threading.Thread(target=compute_sum, args=(num1, num2, result))
thread.start()
thread.join()
if result:
print(f"The sum of {num1} and {num2} is: {result[0]}")
else:
print("Thread did not return a result.")
if __name__ == "__main__":
main()
Sample Runs
Test Case 1:
code
Enter num1: -10
Enter num2: 15
The sum of -10 and 15 is: 5
Test Case 2:
code
Enter num1: 20
Enter num2: 30
The sum of 20 and 30 is: 50
Explanation
Shared List (result): A list is used to store the sum computed by the thread since Python threads cannot return values directly.
Thread Function (compute_sum): Computes the sum and appends it to the result list.
Main Function:
Reads two integers from the user.
Starts the thread, passing num1, num2, and the result list.
Waits for the thread to finish with join.
Retrieves and prints the sum from the result list.
Note: Python's Global Interpreter Lock (GIL) means that threads are subject to certain execution constraints, but for I/O-bound or simple computational tasks like this, it works efficiently.