我正在尝试开发一个在 linux 中具有 c 优先级的多线程程序。所以我的代码如下。当我运行我的程序时,我遇到了“分段错误”。我不知道发生了什么。请帮我。
#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;
}