gpt4 book ai didi

c++ - 在从基类构造函数创建的单独线程中调用纯虚函数

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

#include <unistd.h>
#include <pthread.h>
#include <stdio.h>

class Base {
protected:
pthread_t receiverThreadID;
Base() {
pthread_create(&receiverThreadID,NULL,threadFunction,this);
}
~Base() {

}

virtual void handleEvent() = 0;
static void* threadFunction(void* arg) {
while(true) {
// This threads receives UDP via recvfrom(). The messages can come in randomly. I use sleep() to simulate a blocking wait
sleep(1);
((Base*)arg)->handleEvent();
}
return 0;
}
};

class Derived : public Base {
virtual void handleEvent() {
// Do something
printf("hello\n");
}

public:
Derived() {}
~Derived() {}

};

int main() {
Derived derived;

sleep(10);
}

您不应该从类的构造函数中调用纯虚函数,但是可以在构造函数中创建一个线程,然后调用纯虚函数吗?是否存在竞争条件的风险?上面的代码没有出现任何运行时错误。

如果像我这样写代码不行,你应该怎么解决?

最佳答案

如果 threadFunction()Derived 的构造函数完成之前调用 handleEvent(),这可能会崩溃。

为什么不将 pthread_create 调用放在另一个函数中 - 例如 start() - 并在对象构造完成后调用它?

class Base {
protected:
pthread_t receiverThreadID;
Base() {}
~Base() {}

void start() {
pthread_create(&receiverThreadID,NULL,threadFunction,this);
}

...
};

关于c++ - 在从基类构造函数创建的单独线程中调用纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35463589/

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