I am trying to develop a program which has multithreading with priority by c in linux. So my code is below. When i run my program, i meet "Segmentation fault".I don't know what happend. Please help me.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void *max(void *);
void *avg(void *);
void *min(void *);
int tmp[5];
int main(int argc, char* argv[]){
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_setschedprio(thread1,2);
int i, j;
printf("Input number: \n");
for (j=0; j<5; j++) {
printf("tmp[%d]: ",j);
scanf("%d: ",&tmp[j]);
}
if ((i=pthread_create(&thread1, NULL, max, tmp)) != 0) {
printf("thread creation failed. %d\n", i);
}
if ((i=pthread_create(&thread2, NULL, avg, tmp)) != 0) {
printf("thread creation failed. %d\n", i);
}
if ((i=pthread_create(&thread3, NULL, min, tmp)) != 0) {
printf("thread creation failed. %d\n", i);
}
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
printf("Exiting main\n");
return 0;
}
void *max(void *arg){
int i;
int *arr = (int *)arg;
int max = arr[0];
for(i=1;i<5;i++){
if(max<arr[i]){
max = arr[i];
}
}
printf("Max of array is: %d\n", max);
sleep(1);
return NULL;
}
void *avg(void *arg){
int i;
int *arr = (int *)arg;
int sum =0;
float avg;
for(i=0;i<5;i++){
sum = sum + arr[i];
}
avg = sum/5.0;
printf("Average of array is: %f\n",avg);
sleep(1);
return NULL;
}
void *min(void *arg){
int i;
int *arr = (int *)arg;
int min = arr[0];
for(i=1;i<5;i++){
if(min>arr[i]){
min = arr[i];
}
}
printf("Min of array is: %d\n", min);
sleep(1);
return NULL;
}
You are calling pthread_setschedprio(thread1,2);
when thread1
hasn't been initialized to a valid value. You can set the priority for a thread only after the thread has been created.
To be clear, you should indicate whether or not commenting out the call to pthread_setschedprio(thread1,2)
enables the program to run without crashing. (Also - do you really want the colon in the scanf()
format string?)