gpt4 book ai didi

c++ - pthread_create 的回调函数没有被调用?

转载 作者:行者123 更新时间:2023-11-30 03:40:31 24 4
gpt4 key购买 nike

#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 丢失了

最佳答案

您的 main 提早终止并在创建后立即终止线程。在 main 的 return 0; 之前添加此行:

pthread_join(t1, NULL);

这将使主线程等待(阻塞)t1 的终止。

关于c++ - pthread_create 的回调函数没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37942561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com