簡體   English   中英

通過將結構指針傳遞到C中的pthread_exit()讀取返回的值時出錯

[英]Error reading returned value from passing struct pointer to pthread_exit() in C

我試圖通過pthread_exit()函數將指向結構lower_hyper_id的指針從線程傳遞到主線程,該指針將比較並輸出結構中的值。 但是,當我嘗試使用返回的值並將其強制轉換為結構時,我收到錯誤消息(分段錯誤)。

創建並返回結構的線程:

void *compute(void *arg){
   lower_hyper_id *data = (lower_hyper_id *)malloc(sizeof(lower_hyper_id));

   //some code
   //i debug the program, and at this point, the struct i want
   //to return has the values i want.

   pthread_exit((void *)data);
}

在主要方面:

lower_hyper_id l_hyper_id;

int main(){
    void *ap_state;
    lower_hyper_id values;
    void *ret;

    //some code

    for (int i = 0; i < NUMBER_OF_FILTERING_THREADS; i++)
    {
        s = pthread_join(filtering_threads[i], (void *)&ret);
        //some error checking 

        values = *((lower_hyper_id *)ret);  //this is where i receive the error

        if (values.lowest_cost <= l_hyper_id.lowest_cost)
        {
            l_hyper_id.hyper_id = values.hyper_id;
            l_hyper_id.lowest_cost = values.lowest_cost;
        }
        free(ret);
}

我已經看過stackoverflow中的答案,例如這個問題 ,但是它並沒有幫助我解決這個問題。 我實際上將代碼更改為與此答案中的代碼完全相同,但仍然給我一個錯誤。

您不測試malloc是否返回NULL。 如果您要分配很大的塊,並且分配可能失敗,則可能會出現問題。 除此之外,我不認為問題出在返回值傳遞中。

帶有malloc d指針的pthread_exit()應該可以正常工作。

一個最小的工作示例:

#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void *compute (void *arg)
{
    printf("thread=%llx\n", (unsigned long long)pthread_self());
    size_t sz = strlen("hello world")+1;
    char *ret = malloc(sz+1);
    if(ret) memcpy(ret, "hello world", sz+1);
    return ret;
}
int main()
{
    printf("thread=%llx\n", (unsigned long long)pthread_self());
    pthread_t ptid;
    int er;
    if((er=pthread_create(&ptid,0,compute,0))) return errno=er,perror(0),1;
    void *retval;
    if((er=pthread_join(ptid,&retval))) return errno=er,perror(0),1;
    printf("thread returned: %s\n", (char*)retval);
    free(retval);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM