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

标签 c pointers segmentation-fault pthreads

所以,我正在做一些作业,但我被困在了这个部分。我在尝试调用 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的返回值。它不返回线程 ID。它返回一个错误代码,因此您正在破坏线程 ID 并使您的 pthread_join 调用无效。

关于c - 在 C 中使用 pthread_join 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37302936/

相关文章:

c - 比较字符串和包含土耳其字符的用户输入时,strcmp 函数不起作用

c - 来自两个不同文件的 fscanf

C 中循环的混淆

winapi - 从 vbscript (qtp) 在 win32 dll 中传递一个指针

c - 释放结构给出 0

c - 链表 C 程序导致段错误 :11

c - 初始化一个 in_addr_t 而不进行文本解析

c++ - 是否为空指针未定义行为分配特定内存?

c++ - 奇怪的段错误案例

c - 为什么 strcpy 会触发全局变量的段错误?