【问题标题】:Explanation for behaviour of code代码行为说明
【发布时间】: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 tt 之后有一个未定义的值。而是将其放在 for 循环中。
  • 谢谢 pippin1289。我完全忽略了最常见的怀疑,而是想知道这是否是由于在调用函数时进行了强制转换——这当然是一个无效的怀疑。将 v = (void *)t 移入循环后,它按我预期的方式工作:)

标签: c pointers pthreads


【解决方案1】:

在您的 cmets 之后,您需要从以下位置更改您的代码:

long t;
void* v;
v = (void *)t;
for(...)
  //stuff

到:

long t;
for(...) {
  void* v;
  v = (void*) t;
  //stuff
}

基本上,前一种情况发生的情况是 t 未初始化,因此其值未定义。然后将其复制到变量 v 中并传递给 pthread。如果它在 for 循环内,则 t 已被初始化。

【讨论】:

  • 是的。知道了。我在上面回复了你的评论。非常感谢!
最近更新 更多