C++指针结构和多线程

C++ pointers struct's and multithreading

本文关键字:多线程 结构 指针 C++      更新时间:2023-10-16

请有人向我的阿德勒斯大脑解释为什么炖牛肉不等于 123.222?

为了解释炖牛肉,每个线程的指针变量设置为 123.222,

但是当线程被激活并通过线程函数 null 指针传递指针时,可悲的是每个线程的输出为 0,而不是应有的 123.222。

法典:

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

typedef struct
{
int blossom;
double goulash;
}juniper;
juniper **jeffery;
juniper **james;
typedef struct{
int rodent_teeth;
juniper **raymond;
}rosebud;

void * thread_function(void *p){
juniper *monty = (juniper *) p;
printf("Goulash = %fn",monty->goulash);
}

int main(){
int i;
rosebud *hattys_friend;
hattys_friend = (rosebud*) calloc(1,sizeof(rosebud));
hattys_friend->raymond = (juniper**) calloc(10,sizeof(juniper*));
for(i=0;i<10;i++){
hattys_friend->raymond[i] = (juniper*) calloc(10,sizeof(juniper));
        }
hattys_friend->raymond[2]->goulash = 5.6;
pthread_t threads[10];
for(int i=0;i<10;i++){
hattys_friend->raymond[i]->goulash = 123.222;
hattys_friend->rodent_teeth = i;
pthread_create(&threads[i],NULL,thread_function,(void*) &hattys_friend->raymond[i]);
printf("creating thread %dn",i);
}
for(int i=0;i<10;i++){
pthread_join(threads[i],NULL);

}


jeffery = &hattys_friend->raymond[2];
james = hattys_friend->raymond;



printf("jeffery -> goulash = %fn",(*jeffery)->goulash);

printf("james -> goulash = %fn",(*(james+2))->goulash);
hattys_friend->raymond[2]->goulash = 1.6;
printf("james -> goulash = %fn",(*(james+2))->goulash);

}
void * thread_function(void *p){
    juniper *monty = (juniper *) p;
    printf("Goulash = %fn",monty->goulash);
}

您的thread_function希望收到juniper*,但是

pthread_create(&threads[i],NULL,thread_function,(void*) &hattys_friend->raymond[i]);

hattys_friend->raymond[i]已经是一个juniper*,所以你传递它一个juniper**,访问monty->goulash是未定义的行为。

问题是您将指针传递给指向线程juniper对象的指针。但是,在线程启动例程中,将此指针强制转换为指向 juniper 的指针。这是未定义的行为。