2014-08-28 34 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