我正在嘗試在C++中創建類似於Java線程對象的我自己的線程類。我知道C++不使用實現,所以相反,我在C++線程對象中保留對函數的引用作爲變量。在C++中模擬Java的線程類
我遇到了我的線程對象的第二個構造函數的問題,您作爲我的線程對象的用戶將指定您想要運行的自己的函數。
我得到一個消息,說
Thread.cpp:23:58:錯誤:從無效轉換 '無效()(無效)' 到「無效*()(無效) '[-fpermissive]
#ifndef THREAD_H
#define THREAD_H
#include <iostream>
#include <pthread.h>
#include <cstdlib>
#include <string.h>
class Thread
{
public:
Thread();
Thread(void (*f)(void*));
~Thread();
void* run(void*);
void start();
private:
pthread_t attributes;
int id;
void (*runfunction)(void*); //Remember the pointer to the function
};
void* runthread(void* arg); //header
#endif
這裏是我的C++文件
#include "Thread.h"
Thread::Thread()
{
memset(&attributes,0,sizeof(attributes));
}
Thread::Thread(void (*f)(void*))
{
runfunction = f;
//(*f)();
}
Thread::~Thread()
{
id = pthread_create(&attributes, NULL, runthread,this);
}
void Thread::start()
{
memset(&attributes,0,sizeof(attributes));
id = pthread_create(&attributes, NULL, *runfunction,this);
}
void* Thread::run(void*)
{
}
void* runthread(void* arg)
{
Thread* t = (Thread*) arg;
t->run(NULL);
}
不使用C++ 11線程功能是一個慎重的設計決策?如果沒有,請看看它,因爲我覺得你正在重新發明輪子。 – MariusSiuram 2014-08-28 14:49:07
「C++不使用實現」。其實它只是不關鍵字。 C++中的繼承比Java更靈活,因此「實現」是通過設計而非特定的語言特性發生的。 – Galik 2014-08-28 15:26:28
我認爲我對Java和C++ 11的理解更高一些,因爲我已經理解爲了讓更高層次的程序員更容易使我們的生活更輕鬆所需的東西...... – Matthew 2014-08-28 18:00:20