简体   繁体   English

Linux中c优先的多线程中的“分段故障”

[英]“Segmentation fault” in multithreading with priority by c in linux

I am trying to develop a program which has multithreading with priority by c in linux. 我正在尝试开发一个在Linux中具有c优先级的多线程程序。 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); 您正在调用pthread_setschedprio(thread1,2); when thread1 hasn't been initialized to a valid value. thread1尚未初始化为有效值时。 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. 为了清楚pthread_setschedprio(thread1,2) ,您应该指出是否注释掉对pthread_setschedprio(thread1,2)的调用才能使程序运行而不会崩溃。 (Also - do you really want the colon in the scanf() format string?) (此外-您是否真的想要用scanf()格式的字符串作为冒号?)

here: 这里:

scanf("%d: ",&tmp[j]);

may be this line creating problems, observe : after %d , I don't think so it is the place. 可能是这行产生了问题,请注意: %d ,我认为这不是地方。

May be this is the reason. 可能这就是原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM