Joe*_*ams 1 c++ pthreads race-condition
当我尝试使用虚方法创建一个类实例并将其传递给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;
}
Run Code Online (Sandbox Code Playgroud)
    这里唯一的问题是你在生成的线程执行方法之前删除了对象,所以那时子析构函数已经被触发并且对象不再存在了.
因此它与pthread_create或其他什么无关,它是你的时间,你不能产生一个线程,给它一些资源并在他有机会使用之前删除它们.
试试这个,它将展示在生成的线程使用它们之前主线程如何破坏objs:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
另一方面,如果你只是在删除它们之前在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;
}
Run Code Online (Sandbox Code Playgroud)