1

当我尝试使用虚拟方法创建类实例并将其传递给 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;
}
4

2 回答 2

5

这里唯一的问题是您在生成的线程执行该方法之前删除了对象,因此到那时子析构函数已经触发并且该对象不再存在。

所以它与 pthread_create 或其他任何事情无关,它是你的时机,你不能产生一个线程,给它一些资源并在他有机会使用它们之前删除它们。

试试这个,它将显示在生成的线程使用它们之前,主线程如何破坏 obj:

struct Thread {
pthread_t thread;
bool deleted;

void start() {
    deleted=false;
    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() {
    if(deleted){
        puts("My child deleted me");
    }
    puts("Base");
}
};

struct MyThread : public Thread {
virtual void routine() {

}
~MyThread(){
    deleted=true;
}

};

另一方面,如果您只是在删除它们之前在 main 中放置一个睡眠,那么您将永远不会遇到这个问题,因为生成的线程正在使用有效资源。

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();
    }
    sleep(1);
    for (i=0; i<count; i++)
            delete thread[i];
}

return 0;
}
于 2009-11-26T09:35:46.813 回答
2

不要在析构函数中执行 pthread_join(或任何其他实际工作)。将 join() 方法添加到 Thread 并在 main 中删除 thread[i] 之前调用它。

如果您尝试在析构函数中调用 pthread_join,线程可能仍在执行 Thread::routine()。这意味着它正在使用已经被部分破坏的对象。会发生什么?谁知道?希望程序会很快崩溃。


此外:

  • 如果您希望从 Thread 继承,应将 Thread::~Thread 声明为虚拟的。

  • 检查所有错误并正确处理它们(顺便说一句,不能在析构函数中完成)。

于 2009-11-26T09:57:45.413 回答