這裏是我的main.cpp代碼:C++虛函數和線程
#include <opencv2/opencv.hpp>
using std::string;
#include "caffe_thread_learn.hpp"
class VideoCaptureTest : public InternalThread {
public:
string video;
explicit VideoCaptureTest(string v) : video(v) { StartInternalThread(); }
protected:
virtual void InternalThreadEntry();
};
void VideoCaptureTest::InternalThreadEntry(){
std::cout << "video child" << std::endl;
}
int main(){
InternalThread* vt = new VideoCaptureTest("/Users/zj-db0655/Documents/data/528100078_5768b1b1764438418.mp4");
delete vt;
return 0;
}
caffe_thread.cpp代碼:
#include "caffe_thread_learn.hpp"
InternalThread::~InternalThread() {
StopInternalThread();
}
bool InternalThread::is_started() const {
return thread_ && thread_->joinable();
}
bool InternalThread::must_stop() {
return thread_ && thread_->interruption_requested();
}
void InternalThread::StopInternalThread() {
if (is_started()) {
thread_->interrupt();
try {
thread_->join();
} catch (boost::thread_interrupted&) {
} catch (std::exception& e) {
std::cout << "Thread exception: " << e.what();
}
}
}
void InternalThread::StartInternalThread() {
thread_.reset(new boost::thread(&InternalThread::entry, this));
}
void InternalThread::entry() {
InternalThreadEntry();
}
caffe_thread.hpp代碼
#ifndef caffe_thread_learn_hpp
#define caffe_thread_learn_hpp
#include <stdio.h>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
namespace boost { class thread; }
class InternalThread {
public:
InternalThread() : thread_() {}
virtual ~InternalThread();
/**
* Caffe's thread local state will be initialized using the current
* thread values, e.g. device id, solver index etc. The random seed
* is initialized using caffe_rng_rand.
*/
void StartInternalThread();
/** Will not return until the internal thread has exited. */
void StopInternalThread();
bool is_started() const;
protected:
/* Implement this method in your subclass
with the code you want your thread to run. */
virtual void InternalThreadEntry() { std::cout << "parent" << std::endl; }
virtual void fun() {}
/* Should be tested when running loops to exit when requested. */
bool must_stop();
private:
void entry();
boost::shared_ptr<boost::thread> thread_;
};
#endif /* caffe_thread_learn_hpp */
實際上,輸出是:parant
但是,我想輸出應該是:視頻孩子。因爲當調用VideoCaptureTest中的StartInternalThread時,它會新建一個帶參數(& InternalThread :: entry,this)的線程,並且我認爲這個指向VideoCaptureTest的指針並將調用VideoCaptureTest的InternalThreadEntry輸出視頻子節點。但是,它輸出父項。
謝謝!
解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –