0

writing sample c++ programs related to threads with multiple features in c++. The below program throws a runtime error at t1.join() using a switch statement however it is working plainly. Trying to understand, why it's throwing an error specifically with the switch. Does t1.join() not able to find the thread which started?

terminate called after throwing an instance of 'std::system_error'
  what():  Invalid argument
#include <iostream>
#include <thread>


enum THREAD_CALLBACK_TYPE {
    FUNC_PTR = 1,
    FUNC_OBJ,
    LAMBDA
};

//1. function pointer
void funPtr()
{
    std::cout<<"From func pointer"<<std::endl;
}

//2. function object
class FuncObj
{
    public:
    void operator()()
    {
        std::cout<<"From function object"<<std::endl;
    }

};

//3. lambda

auto Lambda = [](){
    std::cout<<"From Lambda"<<std::endl;
};

int main()
{

    std::cout<< "choose one option \n 1. "
    "Function Pointer\n 2. Function Object\n 3. Lambda\n"<<std::endl;
    std::cout<<"option: "<<std::endl;
    uint8_t option = 0;
    std::cin>>option;

    std::thread t1;
    //t1 = std::thread(Lambda);

    switch (option)
    {
        case FUNC_PTR:
        {
         t1 = std::thread(funPtr);
        }
        break;

        case FUNC_OBJ:
        {
          t1 =  std::thread(FuncObj());
        }
        break;

        case LAMBDA:
        {
          t1 = std::thread(Lambda);
        }
        break;
        
    
    default:
        break;
    }

    t1.join();
}

searched on StackOverflow. no such related questions were posted.

GMudide
  • 109
  • 4
  • Why all this indirection? Anyway, I would use `std::future future;` instead of `std::thread t1; ` and then use `std::async` to launch my functions. E.g. FUNC_OBJ would become `future = std::async(std::launch::async, []{ FuncObj(); });` and join would become `future.get()` – Pepijn Kramer Dec 01 '22 at 06:37
  • 2
    Relevant: https://stackoverflow.com/q/11308898/580083. The problem is that `uint8_t` is a type alias for some character data type (likely `unsigned char`). When you input `1`, it is a character `'1'`, which does not have a numeric value `1`. Consequently, your program goes through the `default` branch of `switch`, which then makes calling `join` invalid. – Daniel Langr Dec 01 '22 at 07:34
  • `uint8_t option = 0;` should be `int option = 0;`. There's no need for this micro-optimization, and it changes the meaning of the code. Unless there's a good reason to do otherwise, use `int` for integer types. – Pete Becker Dec 01 '22 at 15:04

0 Answers0