#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 ;
}
我不断收到浮点异常。我尝试过数据类型自动,size_t, double ,浮点型。目的是显示线程循环。简单的程序将0加到12,并在核心之间分配工作。
最佳答案
尝试更改:
size_t chunk = (end - start + (numthreads - 1))/numthreads ;
t0:
size_t chunk = (numthreads>0 ? (end - start + (numthreads - 1))/numthreads) : end - start)