가상 메서드를 사용하여 클래스 인스턴스를 만들어 pthread_create에 전달하려고하면 호출자가 파생 메서드 대신 기본 메서드를 호출하는 경우가 발생할 수있는 경쟁 조건이 발생합니다. . 검색 후 pthread vtable race
, 나는 이것이 꽤 잘 알려진 행동임을 알게되었습니다. 내 질문은 주위를 둘러 보는 좋은 방법은 무엇입니까?가상 함수와 pthread_create 사이의 레이스
아래 코드는 모든 최적화 설정에서이 동작을 나타냅니다. 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;
}
호기심에서 벗어난 이유는 왜 "클래스"를 '구조체'로 선언하고 있습니까? – mrduclaw
구조체는 기본적으로 모든 멤버를 public으로 만드는 것을 제외하고는 동일한 것을 의미합니다. –
@mrduclaw : 걱정 마세요. 그것은 최근 * class * 대신에 struct *를 사용하기 위해 최근에 관찰 한 유행입니다. 그것은 지나갈 것이다. :-P –