How to start a fixed number of threads all the time

I just started with multithreading. The problem is that my code does not start a new thread after completion, but starts 4 threads after the last 4 is completed, so if tasks take an unequal amount of time, this is not very efficient, and I have thousands of classes to process each time.

Loop() { myClass A,B,C,D; std::thread td1(&myClass::run, &A, args[i]); std::thread td2(&myClass::run, &B, args[i+1]); std::thread td3(&myClass::run, &C, args[i+2]); std::thread td4(&myClass::run, &D, args[i+3]); td1.join(); td2.join(); td3.join(); td4.join(); } 

I found this one , but it didn’t help me at all. I was thinking of using std :: prom, std :: future or std :: packaged_task to keep track of whether a thread ends, but I don't know how to create another thread in its place.

In my case, I just need X threads that run my method with different arguments and their own clean myClass object. I cannot send my calculation work, since it needs all the data that goes into the class.

+5
source share
2 answers

You can try or create a thread pool, but I tried a lot of openflow C ++ 11 ThreadPools, and almost all of them are listening (deadlock or crash at some point) or have a design flaw that makes them useless. You will find about a dozen thread pools on github only.

The simplest solution is to use one (or several) WorkQueue, each thread can add some work to the queue or just process the work (if there are several queues, the thread will try to get the job from each queue, if all the queues are empty, just sleep a little).

Then you just need such a class

 class myClass: public virtual Runnable{ WorkQueue * q; std::atomic<bool> running=true; //used to kill the thread public: myClass(WorkQueue * que):q(que){ } /* IMPLEMENTS: Runnable*/ public virtual void run(){ int i=0; Job * j=nullptr; while(running){ j=q[i]->getNextJob(); if(j){ j->run(); if(j->hasJobsToDispatch()) i++; }else{ i++; } if(i>=queuesNumber) i=0; q[i]->addSomeJob(j->getJobsToDispatch()); } } void stopThread(){ running!=running; } }; 
+3
source

You should examine some kind of thread pool or use std::async (which, depending on your implementation, might use the thread pool below).

+1
source

Source: https://habr.com/ru/post/1200227/


All Articles