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

Dan*_*ida 2 c pointers pthreads segmentation-fault

所以,我正在做一些我的家庭作业而且我被困在这个段上.我试图调用pthread_join时遇到的错误.

我尝试了不同的解决方案,包括创建一个void指针来发送到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;
    }    
}
Run Code Online (Sandbox Code Playgroud)

Fre*_*son 5

你误用了它的返回值pthread_create.它不返回线程ID.它返回一个错误代码,因此您正在破坏线程ID并使您的pthread_join调用无效.