在 C 中使用 pthread_join 时出现分段错误

Segmentation fault when using pthread_join in C

所以,我正在做我的一些家庭作业,但我被困在这个段上。我在尝试调用 pthread_join.

时遇到的错误

我尝试了不同的解决方案,包括创建一个空指针以发送到 pthread_join 调用。

这是我的代码:

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <semaphore.h>
#include <time.h>
#include <pthread.h>

#define NTHREADS 5
#define NVALORES 1000
#define NUMBER_PROCURADO 890

void * run(void *arg);
void fillVector();
int vetor[NVALORES];

int main(){

    int i, vetor2[NTHREADS];
    pthread_t threads[NTHREADS];
    fillVector();
    for (i = 0; i < NTHREADS; i++){
        vetor2[i]=i;
        threads[i]= pthread_create(&threads[i], NULL, run, &vetor2[i]);
    }

    for (i = 0; i < NTHREADS; i++){
        pthread_join(threads[i], NULL);
    }

    return 0;
}

void * run(void * arg){
    int *pos = (int *) arg;

    int i;
    for (i = NVALORES/NTHREADS*(*pos); i < NVALORES/NTHREADS*((*pos)+1); i++){
        if(vetor[i]==NUMBER_PROCURADO){
            printf("Found it! Position: %d\n",i);
        }
        pthread_exit( (void*)pos);
    }
    pthread_exit( (void*)NULL);
}

void fillVector(){
    int i;
    for (i = 0; i < NVALORES; i++){
        vetor[i] = i+1;
    }    
}

您滥用了 pthread_create 的 return 值。它没有 return 线程 ID。它 return 是一个错误代码,因此您正在破坏线程 ID 并使您的 pthread_join 调用无效。