Write two basic C programs to add two numbers. One program using using pthreads
ID: 3798283 • Letter: W
Question
Write two basic C programs to add two numbers. One program using using pthreads and another program using kthreads functions. Students are encouraged to use and enhance the sample code provided below as per their coding standards. This assignment is to learn thread creation and join functions.
Grading information and instructions:
Pthreads program – 10 points
Kthreads program – 10 points
Execution and output Screenshots – 10 points
Sample program structure:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
/* This is our thread function. */
int sum = 0; //Declare a global variable to store the results, sum
void *threadFunc(void* p)
{
//Write your code here to print each variable and sum values
}
int main(void)
{
pthread_t thread1, thread2; // Thread declaration
int *x = malloc (sizeof(*x)); //Use array or two variables as per your convenient
int *y = malloc (sizeof(*y));
*x = 10;
*y = 2;
/* Create worker thread */
//write the thread creation function
/* wait for our thread to finish before continuing */
//write thread join function
printf("main() is running. ");
return 0;
}
Hints:
If you are using an array, create only one thread function to pass an array.
Explanation / Answer
Ans.
#include <stdio.h>
int arr[2];
void *sumPthread(void *arg)
{
int *args_array;
args_array = arg;
int n1,n2,sum;
n1=args_array[0];
n2=args_array[1];
sum = n1+n2;
printf("N1 + N2 = %d ",sum);
return NULL;
}
int main()
{
scanf("%d",&arr[0]);
scanf("%d",&arr[1]);
pthread_t sum;
pthread_create(&sum, NULL, sumPthread, arr);
pthread_join(sum, NULL);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.