【发布时间】:2013-10-13 05:09:09
【问题描述】:
我正在关注多线程教程 https://computing.llnl.gov/tutorials/pthreads 并尝试使用提供的一些代码。
我使用了这个源文件https://computing.llnl.gov/tutorials/pthreads/samples/hello.c 然后将其添加到主函数中:
void * v;
v = (void *)t;
并替换了这一行:
rc = pthread_create(threads+t, NULL, PrintHello, (void*)t);
通过这个:
rc = pthread_create(threads+t, NULL, PrintHello, v)
可以说(我知道这不是一个好的论点:)),输出应该保持不变.. 但这是新的输出:
In main: creating thread 0
In main: creating thread 1
Hello World! It's me, thread #140734232544832!
In main: creating thread 2
In main: creating thread 3
Hello World! It's me, thread #140734232544832!
In main: creating thread 4
Hello World! It's me, thread #140734232544832!
Hello World! It's me, thread #140734232544832!
Hello World! It's me, thread #140734232544832!
线程#是垃圾!
有人可以向我解释这里发生了什么吗?为什么输出会改变?
是不是因为 t 是按值传递并在传递给 PrintHello 时进行强制转换,而现在,在更改之后我试图传递指针并且该指针的地址被正确传递 - 该地址不包含值 t包含,因为那是主要的本地?
有人可以确认/拒绝并修正我的理论吗?
【问题讨论】:
-
您需要向我们展示您在哪里添加了
void* v以及主目录中的以下行 -
啊,当然。 v 得到 t 的值。在
long t、t之后有一个未定义的值。而是将其放在 for 循环中。 -
谢谢 pippin1289。我完全忽略了最常见的怀疑,而是想知道这是否是由于在调用函数时进行了强制转换——这当然是一个无效的怀疑。将 v = (void *)t 移入循环后,它按我预期的方式工作:)