C ++将循环与线程分开

时间:2015-08-17 21:26:21

标签: c++ multithreading

    #include<iostream>
    #include<thread>
    using namespace std ;
    void dowork(size_t s , size_t e, size_t *se )
    {
     for(size_t  i = s ; i < e; i++)
            se += i ;
    }

    int main(void)
    {
        int numthreads = std::thread::hardware_concurrency() ;
        size_t start = 0 ;
        size_t end = 12;
        size_t chunk = (end - start + (numthreads - 1))/numthreads ;
        cout<< chunk ;
        std::thread t[numthreads] ;
        size_t sum = 0 ;
        for(int i = 0 ; i < numthreads ; i++ )
        {
            size_t s = start + i * chunk ;
            size_t e = s + chunk ;
            t[i] = std::thread(dowork, s, e, &sum) ;


        }
        for(int i = 0 ; i < numthreads ; i++)
            t[i].join() ;

        cout<<sum ;



    }

我一直得到浮点异常。我尝试过数据类型Auto,size_t,double,float。目标是显示循环的线程。简单的程序添加0到12并在核心之间划分工作。

1 个答案:

答案 0 :(得分:0)

尝试更改:

size_t chunk = (end - start + (numthreads - 1))/numthreads ;

T0:

size_t chunk = (numthreads>0 ? (end - start + (numthreads - 1))/numthreads) : end - start)