Simulate Java's Thread class in C++

余生颓废 提交于 2019-12-11 09:28:35

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/25551719/simulate-javas-thread-class-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!