簡體   English   中英

嘗試將結構實例傳遞給具有整數和雙精度值的線程函數

[英]Trying to pass an instance of a struct to a thread function with an integer and a double value

我試圖將一個結構的實例傳遞給一個線程,但由於某種原因,它正在為整數打印一個隨機值,但為雙精度打印正確的值?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
//Pass an integer value and a double value to a thread (use struct!)
typedef struct param { 
    int val;
    double db;
}param_t;

void *myth(void *arg) 
{ 
    param_t myT, *myPt;
    myT = *((param_t*)arg);
    myPt = (param_t*)arg;
    
    printf("%d\n", myT.val);
    printf("%.3lf\n", myPt->db);
    pthread_exit(NULL);
}

void main() 
{ 
    pthread_t tid;
    int i = 3733;
    double d = 3733.001;
    param_t t_struct;
    param_t *p;
    p = malloc(sizeof(param_t));
    *p = t_struct;
    t_struct.val = i;
    t_struct.db = d;

    
    pthread_create(&tid, NULL, myth, (void *)&p);
    pthread_join(tid, NULL);
    return;
}

輸出:10969104 3733.001

一個問題在這里:

*p = t_struct;
t_struct.val = i;
t_struct.db = d;

第一個賦值復制未初始化的結構t_struct 然后你初始化t_struct ,但這只會初始化t_struct本身。 不會修改p指向的副本。

然后你通過傳遞一個指向指針的指針使情況變得更糟。 這意味着在線程函數myth ,參數arg根本不指向結構。 當您取消引用指針時,這會導致未定義的行為

我的建議是根本不要理會p或動態分配。 而是傳遞指向原始結構t_struct的指針:

pthread_create(&tid, NULL, myth, & t_struct);

這沒有任何意義:

param_t t_struct;
param_t *p;
p = malloc(sizeof(param_t));
*p = t_struct;       // t_struct isn't initialized, so this is undefined behaviour.
t_struct.val = i;    // Has no effect on `p` or `*p`.
t_struct.db = d;     // Has no effect on `p` or `*p`.

也許你是為了

param_t t_struct;
param_t *p;
p = malloc(sizeof(param_t));
t_struct.val = i;
t_struct.db = d;
*p = t_struct;

下面的會更好:

param_t t_struct;
t_struct.val = i;
t_struct.db = d;

param_t *p = &t_struct;

您還可以使用以下內容:

param_t *p = malloc(sizeof(param_t));
p->val = i;
p->db = d;

與之前的解決方案不同,這最后一個解決方案不需要t_struct在加入線程之前保持存在


還有第二個問題。

arg實際上是param_t ** ,但您將其視為param_t *

固定的:

void *myth(void *arg)   // arg is really a param_t *
{ 
    param_t *p = (param_t*)arg;;
    printf("%d\n", p->val);
    printf("%.3lf\n", p->db);
    pthread_exit(NULL);
}

pthread_create(&tid, NULL, myth, p);

暫無
暫無

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

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