c - pthread_join() 段错误

标签 c segmentation-fault pthreads

我制作这个小程序是为了更多地了解 pthreads。我试图在 10 个线程上计算 0-99 的幂。没有 pthread_join 或当我只加入前 4 个线程时它工作正常。加入任何超过 4 个段的程序。当我加入超过前 4 个线程时,我的程序出现段错误的原因是什么。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>

#define NUM_THREADS 10
double *powr;

void *pows(void *arg){
    int n = *((int*)arg)*10;
    for(int i = n; i < n+10; i++){
        powr[i] = pow(i, 2);
    }
    return NULL;
}

int main(int argc, char *argv[])
{
    pthread_t thread_ID[NUM_THREADS];
    void *exit_status[NUM_THREADS];
    int rank[NUM_THREADS], j;
    powr = (double *)malloc(NUM_THREADS*10);
    for(j = 0; j < NUM_THREADS; j++){
        rank[j] = j;
        pthread_create(&thread_ID[j], NULL, pows, &rank[j]);
    }

    for(j = 0; j < NUM_THREADS; j++){
        pthread_join(thread_ID[j], NULL);
    }

    for(j = 0; j < NUM_THREADS*10; j++){
        printf("%.0lf ", powr[j]);
    }
    return 0;
}

最佳答案

malloc(NUM_THREADS*10); 更改为 malloc(NUM_THREADS*10*sizeof(double)); 后它运行正常。

关于c - pthread_join() 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50554822/

相关文章:

c - 如何使用另一个函数的参数调用一个函数?

c - 只是好奇,为什么这不会导致段错误?

c - inet_ntop 导致段错误

c - 如何在两个线程之间发送中断或信号?

c++ - pthread互斥体的开销?

c++ - 修补 C/C++ 函数以仅返回而不执行

c - 在c中通过套接字原子发送整数

c - C 编程语言 (K & R);回复 : Chapter 1 (EOF)

c - 最简单程序的段错误?

c - 简单 pthread 代码中的奇怪结果