当我尝试使用虚拟方法创建类实例并将其传递给 pthread_create 时,我得到一个竞争条件,导致调用者有时调用基方法而不是像它应该的那样调用派生方法。谷歌搜索后pthread vtable race
,我发现这是相当知名的行为。我的问题是,什么是绕过它的好方法?
下面的代码在任何优化设置下都表现出这种行为。请注意,MyThread 对象在传递给 pthread_create 之前是完全构造的。
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Thread {
pthread_t thread;
void start() {
int s = pthread_create(&thread, NULL, callback, this);
if (s) {
fprintf(stderr, "pthread_create: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}
static void *callback(void *ctx) {
Thread *thread = static_cast<Thread*> (ctx);
thread->routine();
return NULL;
}
~Thread() {
pthread_join(thread, NULL);
}
virtual void routine() {
puts("Base");
}
};
struct MyThread : public Thread {
virtual void routine() {
}
};
int main() {
const int count = 20;
int loop = 1000;
while (loop--) {
MyThread *thread[count];
int i;
for (i=0; i<count; i++) {
thread[i] = new MyThread;
thread[i]->start();
}
for (i=0; i<count; i++)
delete thread[i];
}
return 0;
}