c - "Segmentation fault"在多线程中优先级为 linux 中的 c

标签 c linux multithreading thread-priority

我正在尝试开发一个程序,该程序在 linux 中具有优先级为 c 的多线程。所以我的代码在下面。当我运行我的程序时,我遇到了“Segmentation fault”。我不知道发生了什么。请帮助我。

#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;
}

最佳答案

thread1 尚未初始化为有效值时,您正在调用 pthread_setschedprio(thread1,2);。只有在创建线程后才能设置线程的优先级。

为了清楚起见,您应该指出注释掉对 pthread_setschedprio(thread1,2) 的调用是否能让程序运行而不会崩溃。 (另外 - 你真的想要 scanf() 格式字符串中的冒号吗?)

关于c - "Segmentation fault"在多线程中优先级为 linux 中的 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22522154/

相关文章:

java - 管理 Spring 异步任务执行器中特定方法的线程执行数量

c - C 标准中定义的短语 "declaration of"在哪里,否则应该如何解释它?

c - 背包问题递归函数的意外结果

正则表达式字符恰好出现 x 次

linux - 如何为Linux系统中的特定文件设置密码?

linux - linux/gcc 中是否有 rebase (dll) 命令?

linux - 共享对象可以有自己的线程在后台运行吗?

Visual Studio 中的 C 编程

c - 将数组转换为以一个数组作为成员的结构体是否安全?

c++ - 为什么一个循环比另一个循环需要更长的时间来检测共享内存更新?