3

I want to achieve a similar result:

void somefunc(int var1, char var2){
  dosomething();
}

int main(){
std::thread t1(somefunc, 'a', 3);
return EXIT_SUCCESS;
}

std::thread takes a function pointer and any number of argments. In my class that derives from std::thread I want to initialize std::thread with any number of arguments but I get an error saying:

error: invalid conversion from ‘void (*)()’ to ‘void (*)(...)’ [-fpermissive]
   Thread<> t1(funptr, 30);

but when I remove the dots in the header i get linker errors. I also want to be able to run it with no arguments.

I have the following code(-stdc++17):

threadc.hpp

template </*typename Callable = void*,*/ typename... Args>
class Thread : public std::thread {
public:
    Thread(void (*function)(...), int ms, Args... args)
    :std::thread(/*std::forward<Callable>(function)*/function, ms, std::forward< Args >( args )...)
    {
        t_end = false;
    }
    ~Thread(){
        
    }
    void End(){
        t_end = true;
        if(joinable()){
            join();
        }
    }
    
private:
    void executor(/*Callable function*/void (*function)(...), int ms, Args... args){
        if(ms != 0){
            while(!t_end){
            (*function)(std::forward< Args >( args )...);
            std::this_thread::sleep_for(std::chrono::milliseconds(ms));
            }
        }else{
            (*function)(std::forward< Args >( args )...);
        }

        if(joinable()){
            join();
        }
        //std::async(std::launch::async, [] {
            //});
    }
    
    bool t_end;
};

main.cpp:

void func1(){
  dosomething();
}

void func2(int i){
  dosomething();
}

int main(){
  void (*funptr)() = &func1; // this step can be skipped still no result
  Thread<> t1(funptr, 30); // doesnt work
  Thread<int> t2(func2, 30, 3); // doesnt work
  Thread t2(func2, 30, 3); // doesnt work I want to be able to skip the template parameters like in the std::thread function

  return EXIT_SUCCESS;
}

I would be really thankful if somebody could help me out. I am still a c++ beginner and in highschool:)

  • 3
    `void (*function)(...)` No, `void (*)(...)` is not a "generic function pointer", it's a pointer to a (certain) variadic function. You have to `template Thread(F function)` or similar. Or just use `std::function`. – KamilCuk Jun 25 '20 at 22:42
  • 1
    Normally, one simply uses `std::function` in the executor and generates one via `std::bind`. Also your "wait for execution" is not good as it has large latency - creating a new thread each time is better. Utilize `std::condition_variable` to reuse threads. – ALX23z Jun 26 '20 at 03:37
  • When using the template, can I make the template arguments skipable? In std::thread you don't have to specify them. Or i will just try with std::function. – DominikRzecki Jun 26 '20 at 06:52

0 Answers0