Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

#include <pthread.h> #include <stdio.h> typedef struct param{ int a; int b; int c;…

  1. User

    #include <pthread.h> #include <stdio.h> typedef struct param{ int a; int b; int c; }param;

    size_t THREAD_STACK_DEPTH; pthread_t thread_ids[10]; int i = 0; void plus(void agr){ param agrs = (param*)agr; agrs->c = agrs->b + agrs->a; printf("the test result is %d\n",agrs->c); }

    int main(){ pthread_attr_t attrp; pthread_attr_init(&attrp); pthread_attr_setstacksize(&attrp, THREAD_STACK_DEPTH); param *useagrs;

        for( i=0; i<10; i++) {
            useagrs->a = i;
            useagrs->b = i+1;    
            pthread_create(&thread_ids[i], &attrp, plus, (void*)useagrs);
    }
        for( i=0; i<10; i++) {
            pthread_join(thread_ids[i], NULL);
    }
    

    }这段代码执行出现段错误

  2. Assistant

    在您的代码中,出现段错误的原因是您没有为参数使用agrs分配内存。在main函数中,您声明了一个指向param结构的指针useagrs,但没有为它分配内存。这导致在将useagrs传递给子线程时出现错误。

    为了修复这个问题,您需要为useagrs分配内存。可以通过使用malloc()函数来完成。下面是修复后的代码:

    #include <pthread.h>
    #include <stdio.h>
    #include <stdlib.h> // 添加此头文件
    
    typedef struct param{
        int a;
        int b;
        int c;
    } param;
    
    size_t THREAD_STACK_DEPTH;
    pthread_t thread_ids[10];
    int i = 0;
    
    void plus(void *agr){
        param* agrs = (param*)agr;
        agrs->c = agrs->b + agrs->a;
        printf("the test result is %d\n", agrs->c);
    }
    
    int main(){
        pthread_attr_t attrp;
        pthread_attr_init(&attrp);
        pthread_attr_setstacksize(&attrp, THREAD_STACK_DEPTH);
        param *useagrs;
    
        for(i = 0; i < 10; i++) {
            useagrs = malloc(sizeof(param)); // 分配内存
            useagrs->a = i;
            useagrs->b = i + 1;
            pthread_create(&thread_ids[i], &attrp, plus, (void*)useagrs);
        }
    
        for(i = 0; i < 10; i++) {
            pthread_join(thread_ids[i], NULL);
        }
    
        return 0; // 添加返回值
    }
    

    在修复代码后,您应该不再遇到段错误。现在,代码在创建线程并发送参数时会分配内存,并正确地接收和使用参数。