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

时间:2016-05-18 14:42:16

标签: c pointers segmentation-fault pthreads

所以,我正在做一些我的家庭作业而且我被困在这个段上。我试图调用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;
    }    
}

1 个答案:

答案 0 :(得分:5)

您误用了pthread_join的返回值。它不返回线程ID。它会返回错误代码,因此您会破坏线程ID并使js调用无效。