我剛剛開始學習C++,我正在嘗試使Thread類具有Java Thread類的基本功能。我想要做的是創建一個你繼承的類,編寫一個Run方法(在基類中是純虛擬的)創建子類的對象,調用start方法,並且你有線程。虛擬方法和這個指針
的問題是,在路上我使用C++調度沒有正確完成, - 就像運行函數不是虛擬的,基類的run方法被調用。
這裏是頭
#ifndef _THREAD_H_
#define _THREAD_H_
#include <pthread.h>
class Thread {
public:
Thread();
void Start();
~Thread();
protected:
virtual void Run() = 0;
private:
static void *RunWrapper(void *);
pthread_t thread;
};
#endif
實施
#include "thread.h"
#include <pthread.h>
Thread::Thread() {
}
void Thread::Start() {
pthread_create(&thread, NULL, Thread::RunWrapper, (void *) this);
}
void *Thread::RunWrapper(void *arg) {
Thread *t = (Thread *) arg;
t->Run();
return arg;
}
Thread::~Thread() {
pthread_join(thread, NULL);
}
而這實際上是嘗試做一些事情
#include <iostream>
#include "thread.h"
class MyThread : public Thread {
protected:
void Run() {
std::cout << "The thread is runned" << std::endl;
}
};
int main(void) {
MyThread thread;
thread.Start();
return 0;
}
我不斷收到了錯誤的文件的代碼最近10小時是:
pure virtual method called
terminate called without an active exception
如果您確實想要複製Java功能,請改爲複製java.util.concurrent包。它具有更先進的多線程概念,如執行者,期貨,鎖和互斥鎖。但是,如果你走得很遠,只需使用boost:它已經實現了所有這些東西。 – 2010-10-01 00:46:51