using C coding
write a program that takes the numbers from the array {1,2,3,4,5,6,7,8,9,10} and uses 2 threads at the same time. One thread will find the addition of the numbers, and the other will find the multiplication of the numbers. The two different threads will run at the same time and will have an end run of:
the addition is: 55
the multiplication is: 3628800
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //Header file for sleep(). man 3 sleep
for details.
#include <pthread.h>
// size of array
#define MAX 16
// maximum number of threads
#define MAX_THREAD 4
int a[] = { 1,2,3,4,5,6,7,8,9,10 };
int sum=0;
int mul=1;
void* sum_array(void* arg)
{
// Each thread computes sum of 1/4th of array
for (int i =0;i<10; i++)
sum =sum+a[i];
}
void* mul_array(void* arg)
{
// Each thread computes sum of 1/4th of array
for (int i =0;i<10; i++){
mul =mul* a[i];
}
}
// Driver Code
int main()
{
pthread_t threads[2];
// Creating 4 threads
pthread_create(&threads[0], NULL, sum_array,
(void*)NULL);
pthread_join(threads[0], NULL);
pthread_create(&threads[1], NULL, mul_array,
(void*)NULL);
pthread_join(threads[1], NULL);
printf("the addition is: %d\n",sum);
printf("the multiplication is %d\n",mul);
return 0;
}
===================================
akshay@akshay-Inspiron-3537:~/CODE$ gcc pthread.c -pthread
akshay@akshay-Inspiron-3537:~/CODE$ ./a.out
the addition is: 55
the multiplication is 3628800
Get Answers For Free
Most questions answered within 1 hours.