C++指针结构和多线程
C++ pointers struct's and multithreading
请有人向我的阿德勒斯大脑解释为什么炖牛肉不等于 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
的指针。这是未定义的行为。
相关文章:
- 在C++中使用cURL和多线程
- 多线程双缓冲区
- 为什么我的多线程作业队列崩溃
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 为什么一个向量上的多线程操作很慢
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 全局变量 多读取器 一个写入器多线程安全?
- boost::文件系统::recursive_directory_iterator多线程安全
- 如何阻止TensorFlow的多线程
- 如何在多线程中正确使用unique_ptr进行多态性?
- 多线程和共享资源:使用C++定期将数据从缓冲区(数据结构)复制到文件
- 在多线程程序中创建OpenGL结构
- 使用 MFC 的结构多线程
- C++指针结构和多线程
- 为多线程将结构内存分配给参数
- 多线程插件体系结构中的共享、单侧可变状态
- 需要帮助模板化多线程访问的结构
- 一种使用多线程在巨大树形结构中查找文件的方法
- 如何在多线程环境下安全地访问结构字段