仮想メソッドを使用してクラスインスタンスを作成し、それを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;
}