2012-03-10 94 views
0

我是新来的,并用pthread编程noob。 我的问题是在一个C++类,我试图创建封装线程。 阅读我看到,当我创建一个pthread时,我需要将C函数传递给它在启动时运行的pthread_create ...因此,当pthread运行该函数时,它不会在标准输出上输出消息!没有cout打印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 

我希望有人明白了! 对不起我的英文! :) Inzirio

回答

0

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

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

+0

谢谢我会试试!我不会那么想! ;) – inzirio 2012-03-10 16:21:17