pthread_join 的分段错误核心转储

问题描述

我正在尝试运行这个文件,但它给出了这个错误。 出现分段错误(核心转储)。 pthread_join 的分段错误(核心转储)。 试过在所有地方运行 printf 并觉得这一定是错误

enter image description here

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <math.h>
#include <pthread.h>

float etime();
char *buffer;
void *foo(int kb)
{
    printf("Allocating memory\n");
    buffer = calloc(kb,sizeof(char));
    printf("Memory allocated\n");
    int i;
    printf("After i\n");
    for(i=0;i<kb;i++)
    {
        buffer[i]='z';
    }
    printf("End of for loop\n");
}
    
void et(int size)  
{
    
    int thrr;
    pthread_t num;
    etime();
    printf("Inside et \n");
    printf("Before calling create thread \n");
    thrr=pthread_create(&num,NULL,foo(size),NULL);
    printf("thrr = %d\n",thrr);
    if(thrr!=0)
    {
        printf("Cannot create thread!\n");
    
    }
    else
    {
        printf("Thread created successfully\n");
    
    }
    pthread_join(num,NULL);
    
    printf("Time taken = %f\n",etime());
}
    

解决方法

pthread 处理程序的签名是 void *handler(void *)

切换自

void *foo(int kb)

void *foo(void *kb)

使用指向数据的指针调用处理程序:

thrr = pthread_create(&num,NULL,foo,&size);

然后,在处理程序中获取传递的 int 的值:

void *foo(void *data)
{
    int kb = *(int *)data;

您还需要注意 size 超出范围,只要有可能尝试传递常量值,即:

thrr = pthread_create(&num,(void *)(uintptr_t)size);

然后,在处理程序中:

void *foo(void *data)
{
    int kb = (int)(uintptr_t)data;

uintptr_t 需要 #include <inttypes.h>