【问题标题】:No cout printing in pthread starting functionpthread 启动函数中没有 cout 打印
【发布时间】:2012-03-10 23:47:35
【问题描述】:

我是新来的,并且是 pthread 编程的菜鸟。 我的问题是在一个 C++ 类中,我试图创建它来封装一个线程。 阅读周围我发现,当我创建一个 pthread 时,我需要将一个 C 函数传递给它在启动时运行的 pthread_create ......所以,当 pthread 运行该函数时,它不会在标准输出上输出消息!

但是如果你看到代码会更好: (显然是从网络教程复制粘贴的^^)

void *runAtStart( void *threadid)
{

    long tid;
   tid = (long)threadid;

   printf("Hello World! It's me, thread #%ld!\n", tid);
   pthread_exit(NULL);
}


Thread::Thread() {
    pthread_t threads[1];
   int rc;
   long t;
   for(t=0; t<1; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, runAtStart, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
        // exit(-1);
      }
   }
}

主要我称之为:

int main()
{
    Thread *th=new Thread();
    return 0;
}

生成的输出是:

In main: creating thread 0

希望有人理解! 对不起我的英语不好! :) 因齐里奥

【问题讨论】:

    标签: pthreads cout


    【解决方案1】:

    您的程序运行良好。您看到的问题是您的 main() 函数在您的线程实际运行之前返回,这会导致您的程序退出。

    证明这一点的一个简单方法是在您的回电之前在main() 中添加sleep(5);。一个更好的方法是找到一种方法让 main() 等到它的所有线程都完成后才返回。一种合理的方法是向执行 pthread_join 的 Thread 类添加析构函数,并确保您实际调用了析构函数:delete th;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2021-08-03
      • 2011-01-05
      • 2020-01-10
      • 1970-01-01
      相关资源
      最近更新 更多