2. Thread Group

2. Thread Group_第1张图片
ThreadGroup
  • 这个编辑器不支持直接插入整块的代码,使用起来稍微有些不方便。

由于线程支持移动的特性,那么就可以构建一系列线程并放到一个容器中(该容器需要是移动感知的,更新后的std::vector便是移动感知),进行自动管理。
可移动(movable)而非可复制的(copyable)可以将对象的所有权进行转移,比如ifstream、unique_ptr、thread都是这样的资源类型

#include "ThreadGroup.h"
#include 

using namespace std;

void NormalDoWork(unsigned id)
{
    cout << "print number :" << id << " Thread Number:" << this_thread::get_id() << endl;
}

void CThreadGroup::doWork(unsigned id)
{
    //lock_guard guard(dataMutex);
    cout << "print number :" << id << " Thread Number:" << this_thread::get_id() << endl;
}

 void CThreadGroup::runThreadGroup()
{
    size_t length = 10;
    for (size_t i = 0; i < length; i++)
    {
        threadGroup.push_back(thread(&CThreadGroup::doWork, this, i));
        //threadGroup.push_back(thread(doWork, i)); // 如果doWork是个static函数,也可以这样使用
        //threadGroup.push_back(thread(NormalDoWork, i));
    }

    for_each(threadGroup.begin(), threadGroup.end(), mem_fn(&thread::join));
 }

书上还有稍微复杂一些的例子,可以实现对容器进行分组后多线程并行计算。

#include      // std::cout
#include    // std::minus
#include       // std::accumulate
#include      // std::distance
#include 
#include 
#include 

template
struct accumulate_block
{
void operator()(Iterator first, Iterator last, T& result)
{
    result = std::accumulate(first, last, result);
}
};

template
T parallel_accumulate(Iterator first, Iterator last, T init)
{
unsigned long const length = std::distance(first, last);
if (!length)
{
    return init;
}

unsigned long const min_per_thread = 25;
unsigned long const max_threads = (length + min_per_thread - 1) / min_per_thread;
unsigned long const hardware_threads = std::thread::hardware_concurrency();
unsigned long const num_threads = std::min(hardware_threads != 0 ? hardware_threads : 2, max_threads);
unsigned long const block_size = length / num_threads;

std::vector results(num_threads);
std::vector threads(num_threads - 1);

Iterator block_start = first;
for (unsigned long i = 0; i < num_threads - 1; ++i)
{
    Iterator block_end = block_start;
    std::advance(block_end, block_size);
    threads[i] = std::thread(accumulate_block(), block_start, block_end, std::ref(results[i]));
    block_start = block_end;
}

accumulate_block()(block_start, last, results[num_threads - 1]);
std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));

return std::accumulate(results.begin(), results.end(), init);
}

void testParallelAccumulate()
{
    int array_data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::vector datas(array_data, array_data + sizeof(array_data) /  sizeof(int));
    int result = 0;
    std::cout << "Results is: " <<
    parallel_accumulate::iterator, int>(datas.begin(), datas.end(), result) << std::endl;
}

你可能感兴趣的:(2. Thread Group)