在C++中模拟Java的Thread类

Simulate Java's Thread class in C++

本文关键字:Thread Java 模拟 C++      更新时间:2023-10-16

我正试图在C++中创建自己的Thread类,该类类似于Java Thread对象。我知道C++不使用实现,所以我在C++线程对象中保留了对函数的引用作为变量。

我在线程对象的第二个构造函数中遇到了问题,作为线程对象的用户,您需要指定自己要运行的函数。

我收到一条信息,上面写着

线程.cpp:23:58:错误:从"void()(void

#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);
}

pthread_create需要一个函数,其中一个void*参数返回void*,而您提供的函数返回void

但是,正如评论所说,使用C++内置线程是更好的选择。