2014-08-28 57 views
1

我正在嘗試在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); 
} 
+4

不使用C++ 11線程功能是一個慎重的設計決策?如果沒有,請看看它,因爲我覺得你正在重新發明輪子。 – MariusSiuram 2014-08-28 14:49:07

+0

「C++不使用實現」。其實它只是不關鍵字。 C++中的繼承比Java更靈活,因此「實現」是通過設計而非特定的語言特性發生的。 – Galik 2014-08-28 15:26:28

+0

我認爲我對Java和C++ 11的理解更高一些,因爲我已經理解爲了讓更高層次的程序員更容易使我們的生活更輕鬆所需的東西...... – Matthew 2014-08-28 18:00:20

回答

2

pthread_create需要一個返回void*的參數爲void*的函數,並提供返回void的函數。

但是,正如評論所說,使用C++內置線程是更好的選擇。

+0

您對我的代碼有什麼建議嗎?我不明白如何解決它。我試圖將函數作爲參數與線程結合起來。 至於不使用內置的一個,我還沒有探索,並希望舒適的老派學校線程先工作。 – Matthew 2014-08-28 15:07:08

+0

@Matthew:因爲這個答案和錯誤消息都說:要修復它,改變函數指針的類型('runfunction'和構造函數參數'f')以返回void *'not'void',因爲這就是'pthread_create'所期望的。 – 2014-08-28 15:14:31

+0

當我這樣做時,我不能再傳入一個函數作爲參數。 http://stackoverflow.com/questions/9410/how-do-you-pass-a-function-as-a-parameter-in-c – Matthew 2014-08-28 15:18:33