我正在尝试在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