使用std :: thread将多个线程的数组组合在一起使用std :: thread

Posted Overboom

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用std :: thread将多个线程的数组组合在一起使用std :: thread相关的知识,希望对你有一定的参考价值。

#include <iostream> 
#include <vector> 
#include <thread> 
#include <mutex> 
#include <cassert> 
#include "boost/multi_array.hpp" 

std::vector<float> Array; 
std::mutex Array_mutex; 

void Summation(int sample_size) 
 
    std::lock_guard<std::mutex> guard(Array_mutex); 
    for(int i = 0; i < sample_size; i++) 
     
     Array.push_back(rand() % 10 + 1); 
     
    std::cout << "\\n"; 
 

int main(int argc, const char * argv[])  
    int sample_size = 10; 
    int Num_Threads = 2; 
    int number_count = sample_size/Num_Threads; 
    srand(time(NULL)); 
    std::vector<std::thread> Threads; 
    for(int i = 0; i < Num_Threads; i++) 
     
     Threads.push_back(std::thread(Summation,number_count)); 
     

    for(int i = 0; i < Num_Threads; i++) 
     
     Threads[i].join(); 
     

    // - I would like to combine the arrays produced from each thread into a 
    // single array, where each element in the final array is the sum of 
    // the identical element in the array from each thread 

    // i.e. Element 1(final) = Element 1(thread 1) + Element 1(thread2) 
    //  Element 2(final) = Element 2(thread 1) + Element 2(thread2) 
    //  Element 3(final) = Element 3(thread 1) + Element 3(thread2) 

    return 0; 
 

以上是关于使用std :: thread将多个线程的数组组合在一起使用std :: thread的主要内容,如果未能解决你的问题,请参考以下文章