代码行为的说明

时间:2013-10-13 05:09:09

标签: c pointers pthreads

我正在关注多线程教程 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包含,因为那是本地的主?

有人可以确认/拒绝并修复我的理论吗?

1 个答案:

答案 0 :(得分:1)

发表评论后,您需要更改以下代码:

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

为:

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

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