简体   繁体   English

pthread_join()segfault

[英]pthread_join() segfault

I made this little program to understand pthreads a bit more. 我编写了这个小程序,以更多地了解pthread。 I tried to compute the powers of 0-99 over 10 threads. 我尝试在10个线程上计算0-99的幂。 It works fine without pthread_join or when I join only the first 4 threads. 如果没有pthread_join或仅加入前四个线程,它可以正常工作。 Joining anything above 4 segfaults the program. 如果加入高于4的任何段,则将导致该程序。 What is the reason my program segfaults when I am joining more than the first 4 threads. 当我加入多个前四个线程时,我的程序出现段错误的原因是什么?

#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;
}

after changing malloc(NUM_THREADS*10); 更改malloc(NUM_THREADS*10); to malloc(NUM_THREADS*10*sizeof(double)); malloc(NUM_THREADS*10*sizeof(double)); it runs correctly. 它可以正常运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM