Thread Task2.c

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

#include<stdio.

h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
pthread_t a_thread;
struct thread_data{
int* num;
int count;
int result;
};
void*findavg(void*arg){
struct thread_data*data = (struct thread_data*)arg;
int sum=0;
for(int i=0;i<data->count;i++){
sum=sum+data->num[i];
}

data->result=sum/(double)data->count;

return NULL;
}
int main(int argc, char*argv[]){
if(argc<2){
printf("Error you entered less arguments\n");
return 1;
}
int count=argc-1;
int*numbers=malloc(count*sizeof(int));
if(!numbers){
perror("Failed to allocate Memory \n");
return 1;
}

for(int i=0;i<count;i++){
numbers[i]=atoi(argv[i+1]);
}
struct thread_data data;
data.num=numbers;
data.count=count;
data.result=0;

if(pthread_create(&a_thread,NULL,&findavg,(void*)&data)!=0){
perror("Failed! \n");
return 1;
}

pthread_join(a_thread,NULL);
printf("The avg value of numbers are %d\n", data.result);

You might also like