Create variable number of std::threads

旧城冷巷雨未停 提交于 2020-01-06 03:49:25

问题


I have a threaded program that I have to run on multiple computers. Each of them have a different number of supported threads. In the computer that I developed the program there are 4 threads , and so I hard coded 4 threads to be created. I want to make this vary according to the situation . I want to use std::thread::hardware_concurrency to get the number of threads , and divide the work into the number of threads available . Is this possible ?

The hard coded thread creation is :

   //const unsigned int SIZE = std::thread::hardware_concurrency ;
    const unsigned int SIZE = 4 ;

        void zeroOut(std::vector<obj> vec , int start , int end)
       {
      // Does an operation on vec from start index to end index
       }
        int main() {
            std::vector<obj_thread>  vec ;
            // Do some work on vec. Fill it with values. 
                unsigned int step = vec.size()/SIZE;
                std::thread thread1(zeroOut,vec,step,step*2);
                std::thread thread2(zeroOut,vec,step*2,step*3);
                std::thread thread3(zeroOut,vec,step*3,step*4);
                zeroOut(vec, 0 , step);
                thread1.join();
                thread2.join();
                thread3.join();
            return 0 ; 
            }

I am thinking of using a std::vector , but I am new to multi threaded programming and don't know how do it.

Thank you for your time.


回答1:


Is this possible ?

Yes.

I am thinking of using a std::vector

Good idea. That's exactly what I recommend you to use. The number of threads in a vector can vary during runtime.

but I am new to multi threaded programming and don't know how do it.

You only use the vector of threads in the original main thread that creates the other threads. Since you use the vector in a single thread, it's use doesn't differ in any way from using a vector in a single-threaded program.



来源:https://stackoverflow.com/questions/33941508/create-variable-number-of-stdthreads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!