pthread_create的回调函数没被调用?

时间:2016-06-21 10:57:18

标签: c++ multithreading

#include <iostream>
#include <pthread.h>

using namespace std;

class Base

{
    private:
    public:

        void threadCall1( void * value)
        {
            cout<<"inside threadCall1"<<endl;
            cout<<"Value is"<<(int *)value<<endl;

        }

    protected:

};

class Derived
{
    private:
    public:
        void threadCall2 ();
    protected:



};

void *passValue(void * q)
{

    cout<<"inside passValue"<<endl;
    Base *b = new Base();
    b->threadCall1(q);
    cout<<"after threadCall1"<<endl;
    Derived *d;
    cout<<(int *)q<<endl;
    pthread_exit(NULL);
}

 void Derived::threadCall2()
{
    cout<<"inside threadCall2"<<endl;

}
int main ()
{
    int k = 2;
    pthread_t t1;
    cout<<"inside main"<<endl;

    pthread_create(&t1,NULL,&passValue,(void *)k);
    cout<<"after pthread_create"<<endl;
    return 0;
}

输出:

inside main
after pthread_create

一切似乎都很好,但不知道为什么passValue没有被调用,我得到了上面的输出,但缺少其他日志inside passValue

1 个答案:

答案 0 :(得分:2)

您的main会提前终止并在创建后立即杀死该主题。在主要return 0;之前添加此行:

pthread_join(t1, NULL);

这将使主线程等待(块)终止t1

相关问题