스레드 작성시 OS 스케줄러에 세금이 부과되는 이유 & 파괴? (이러한 작업은 비용이 많이 듭니다.) 대신 스레드가 더 많이 작동하도록하십시오.
편집 : 동일한 청크로 작업을 분할하고 싶지 않으면 가장 좋은 해결책은 실제로 스레드 풀입니다. 참고로 thread_pool library in the works for C++14이 있습니다.
다음은 동등한 청크로 작업을 나눌 수 있다고 가정하므로 질문에 정확하게 적용되지 않습니다. 편집 끝. @Igor Tandetnik이 코멘트에 알 수 있듯이
struct matrix
{
int nrows, ncols;
// assuming row-based processing; adjust for column-based processing
void fill_rows(int first, int last);
};
int num_threads = std::thread::hardware_concurrency();
std::vector<std::thread> threads(num_threads);
matrix m; // must be initialized...
// here - every thread will process as many rows as needed
int nrows_per_thread = m.nrows/num_threads;
for(int i = 0; i != num_threads; ++i)
{
// thread i will process these rows:
int first = i * nrows_per_thread;
int last = first + nrows_per_thread;
// last thread gets remaining rows
last += (i == num_threads - 1) ? m.nrows % nrows_per_thread : 0;
threads[i] = std::move(std::thread([&m,first,last]{
m.fill_rows(first,last); }))
}
for(int i = 0; i != num_threads; ++i)
{
threads[i].join();
}
이 당신이 매우 자주 할 작업이 경우, 작업자 풀을 사용합니다. 일회성으로 인해 문제가되지 않습니다.
'기존 스레드가 끝나면 새 스레드를 생성 할 수 있습니다 .' 왜? 기존의 스레드가 즉시 더 많은 작업을 수행 할 수있을 때 한 스레드가 즉시 다른 스레드를 작성하도록하는 점은 무엇입니까? 작업 항목의 대기열을 만들고 작업자 스레드 풀이 해당 대기열의 항목을 선택하여 처리하도록하십시오. –
그것은 총체적인 감각을 만든다! 감사! – mskb