简体   繁体   English

pthread_create的回调函数无法调用?

[英]Callback function of pthread_create not getting called?

#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;
}

Output: 输出:

inside main
after pthread_create

Everything seems fine but don't know why passValue is not getting called and I get the above output but other logs namely inside passValue is missing 一切似乎都很好,但是不知道为什么未调用passValue ,我得到了上面的输出,但是缺少其他日志,即inside passValue

Your main terminates early and kills the thread immediately after creation. 您的main线程提早终止,并在创建后立即终止线程。 Add this line before return 0; return 0;之前添加此行return 0; of the main: 主要:

pthread_join(t1, NULL);

This will make the main thread wait for (blocks) for the termination of t1 . 这将使主线程等待(块)终止t1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM