In: Computer Science
Thread Programming (C Programming)
Objective
Develop threads: thread and main.
Functionality of Threads:
The main program accepts inputs from the user from the console. The user can provide the following two types of input:
Here, num1 and num2 are two integer numbers.
E.g., the user may input add 1 2.
The threads receive the command along with the number, and performs the appropriate arithmetic operation and returns the results to main program. The main program then prints the results to the console. (The main program spawns 2 threads. The input from the user is then sent to the threads. One thread will do addition operation and the other one will do multiplication operation. The results will be sent back to the main program and print them out.)
Example of the threads usage.
Read Input Data for calculator Program
Create New Thread 0 for arithmetic operation.
Thread Started ID 0xb7ddab90
Lock Results for new operation:
Unlock Results after finishing new operation.
Result of add 1 and 2 = 3.00
Arithmetic operation Thread Stopped
Create New Thread 1 for arithmetic operation.
Thread Started ID 0xb75d9b90
Lock Results for new operation:
Unlock Results after finishing new operation.
Result of mult 3 and 4 = 12.00
Arithmetic operation Thread Stopped
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void *sum_thread(void *arg)
{
int *args_array;
args_array = (int *)arg;
int n1, n2, res;
n1 = args_array[0];
n2 = args_array[1];
res = n1 + n2;
int *p = (int *)malloc(sizeof(int));
*p = res;
pthread_exit(p);
}
void *mult_thread(void *arg)
{
int *args_array;
args_array = (int *)arg;
int n1, n2, res;
n1 = args_array[0];
n2 = args_array[1];
res = n1 * n2;
int *p = (int *)malloc(sizeof(int));
*p = res;
pthread_exit(p);
}
int main()
{
pthread_t tid_sum, tid_mult;
char s[100];
int input[2];
scanf("%s", &s);
scanf("%d", &input[0]);
scanf("%d", &input[1]);
void *res;
if (s[0] == 'a' || s[0] == 'A')
{
pthread_create(&tid_sum, NULL, sum_thread, input);
pthread_join(tid_sum, &res);
}
else
{
pthread_create(&tid_mult, NULL, mult_thread, input);
pthread_join(tid_mult, &res);
}
int *output = (int *)res;
printf("result of %s %d and %d = %d", s, input[0], input[1], *output);
return 0;
}
Output: