Search code examples
c++multithreadingc++11stdthread

dynamic thread creation using std::thread in c++


How we can Create dynamic threads using std::thread. Actually I am accessing some raw string from a queue and have to perform some processing on that and the queue is having thousands of such messages, so i want to create a thread for each message to improve the performance. I can create the thread's using below code.

unsigned int n = std::thread::hardware_concurrency();
std::thread myThreads[n];
while(true)
{


    for (int i=0; i<n; i++){
        myThreads[i] = std::thread(&ControlQueue::processSomeStuff,this,msg_struct);
        }



//for joining
for (int i=0; i<n; i++){
    myThreads[i].join();
}
}

but the thing is if I use the above code then it will create the threads only for que.size() threads, but the queue will have some more new messages.

So is there any method for creating a thread for each new message dynamically. like server socket creates a new socket for processing the client request.


Solution

  • This looks like a good case for a thread pool: a set of threads is pre-created and ready to execute the jobs.

    When a new message is received then the app passes it to the thread pool for further processing and immediately starts waiting for the next message.

    A thread pool implementation I have done some time ago may be found here https://codereview.stackexchange.com/questions/36018/thread-pool-on-c11 on the Codereview site.