在C ++中模拟Java的Thread类 [英] Simulate Java's Thread class in C++
问题描述
我试图在C ++中创建类似于Java Thread对象的自己的Thread类。我明白C ++不使用实现所以,我保持一个函数作为一个变量在我的C + +线程对象的引用。
我遇到麻烦我的线程对象的第二个构造函数,你作为我的线程对象的用户要指定你想要运行的自己的函数。 p>
我收到一条消息,表示
Thread.cpp:23:58:error:invalid conversion从'void()(void )'到'void *()(void )'[-fpermissive] b $ b
#ifndef THREAD_H
#define THREAD_H
#include< iostream>
#include< pthread.h>
#include< cstdlib>
#include< string.h>
类线程
{
public:
Thread();
Thread(void(* f)(void *));
〜Thread();
void * run(void *);
void start();
private:
pthread_t attributes;
int id;
void(* runfunction)(void *); //记住函数的指针
};
void * runthread(void * arg); // header
#endif
C ++档案
#includeThread.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 * arg)
{
Thread * t =(Thread *)arg;
t-> run(NULL);
}
pthread_create
需要一个函数,其中一个 void *
参数返回 void *
函数返回 void
。
但是,如注释所说,使用C ++内置线程是更好的选择。
I am attempting to create my own Thread class in C++ that resembles the Java Thread object. I understand that C++ does not use implementation so instead I am keeping a reference to a function as a variable in my C++ Thread Object.
I am having trouble with the second constructor of my Thread Object where you as the user of my thread object are to specify your own function that you want to run.
I am getting a message that says
Thread.cpp:23:58: error: invalid conversion from ‘void ()(void)’ to ‘void* ()(void)’ [-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
And here is my C++ file
#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);
}
pthread_create
expects a function with one void*
parameter returning void*
, and you provide a function returning void
.
But, as comments say, use C++ builtin threading is better option.
这篇关于在C ++中模拟Java的Thread类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!