作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
#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/
我是一名优秀的程序员,十分优秀!