dimanche 20 mars 2022

std::binding a loop variable to a lambda and executing it with a std::async

I have a fairly simple scenario:

int num_threads = 4;
auto my_helper = [&](const int thread_number) -> int {
    return thread_number;
};

std::future<int> futures[num_threads];
for (int i = 0; i < num_threads; i++) {
  futures[i] = std::async(std::launch::async, std::bind(my_helper, i));
}

for (int i = 0; i < num_threads; i++) {
  futures[i].wait();
  printf("%d\n", futures[i].get());
}

This prints out:

1
2
3
4

and not the expected:

0
1
2
3

I thought it was something to do with i being bound as a reference, so I changed to std::launch::deferred instead of std::launch::async, but I get the same result.

Why is my integer being incremented unexpectedly?

Aucun commentaire:

Enregistrer un commentaire