请有人可以向我的 adlers 大脑解释为什么炖牛肉不等于 123.222?
为了解释 goulash 是为每个线程设置为 123.222 的指针变量,但是当线程被激活并通过线程函数空指针传递指针时,每个线程的输出可悲的是 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 = %f\n",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 %d\n",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 = %f\n",(*jeffery)->goulash);
printf("james -> goulash = %f\n",(*(james+2))->goulash);
hattys_friend->raymond[2]->goulash = 1.6;
printf("james -> goulash = %f\n",(*(james+2))->goulash);
}