mardi 4 avril 2017

Equally divide task to threads according to hardware concurrency

I'm trying to run this simple program and wondering why the output is coming wrong. The code queries for hardware concurrency, then tries to launch that amount of threads and do some task. To stub that task, I'm writing to individual elements of already resized vector, but the result is still coming wrong -

#include <iostream>
#include <thread>
#include <vector>
#include <functional>

void myMethod(std::vector<int> &v, int threadNumber) {
    for(int i = threadNumber - 1; i < v.size(); i+= threadNumber) {
        v[i] = threadNumber;
    }
}

int main() {
    const auto numThread = std::thread::hardware_concurrency();
    std::vector<int> vec;
    vec.resize(100, 0);

    if(numThread < 2) {
        std::cout << "Not running\n";
        return 0;
    }

    std::vector<std::thread> vT;
    for(int i = 1; i <= numThread; ++i) {
        vT.emplace_back(myMethod, std::ref(vec), i);
    }
    for(auto &t: vT) { t.join(); }


    for(const auto &i: vec) {
        std::cout << i << ' ';
    }
    std::cout << std::endl;
}

Output comes as -

1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4 1 3 1 4 3 2 1 4 1 2 3 4

but I was expecting - 1 2 3 4 1 2 3 4 ...

Aucun commentaire:

Enregistrer un commentaire