0

Started learning c++ threads. I have a problem but not sure if my solution would work. I need an application that create threads but run their functions on demand.

Lets say I create 4 threads from the main thread (main function).

Take this minimal example.

int main (){
    int numThreads;
    cin >> numThreads;
    for (int i = 0; i < numThreads; i++) {
      threadList[i] = std::thread(SomeClass);
    }
    while (true) {
        int i;
        cout << "Enter thread to execute from";
        cin >> i;
        cout << "Execute function of specific thread ";
        someresponse = threadList[i].executeSomeClassFunction(); // execute specific thread function
        cout << "Got some Response " << someresponse;
    }
  return 0;
}

Is it possible to implement something like this? The question I have is how I let the thread know what to execute.

drescherjm
  • 10,365
  • 5
  • 44
  • 64
kg99
  • 117
  • 1
  • 11
  • This sounds like you want a threadpool however I am not sure its beginner material. Related: [https://stackoverflow.com/questions/15752659/thread-pooling-in-c11](https://stackoverflow.com/questions/15752659/thread-pooling-in-c11) – drescherjm Oct 22 '20 at 13:00
  • As you are a beginner I suggest not using threads or multithreading. is there a specific reason why you need the function to run in a thread? – RoQuOTriX Oct 22 '20 at 13:01
  • ***but not sure if my solution would work*** Your solution would not work. You would execute the function in the main thread in each case. – drescherjm Oct 22 '20 at 13:02
  • 2
    Possible solutions are threadpools, as already mentioned, or possibly [`std::async`](https://en.cppreference.com/w/cpp/thread/async) or similar. – Some programmer dude Oct 22 '20 at 13:08
  • Okay, I just wanted to know whether is possible. While reading about threads, I saw that I can create a shared structure, queue for instance, let the threads sit in a loop, when there is data run some function with the data. But I was thinking of running a specific thread on demand. – kg99 Oct 22 '20 at 13:11
  • @kg99 the threads block until the work queue contains a job for them to do. – Richard Critten Oct 22 '20 at 13:21

0 Answers0