mardi 28 juin 2016

Concurrency with stateful algorithms


As I was considering this question, I realized that the issue is actually a general question about concurrency.

My issue started with looking for a way to use a future in conjunction with a vector of random numbers. I have been using futures for other parts of my code.

Here, I needed:

std::vector<std::vector<int>> vector_of_random_ints;

The problem, as noted in the subject, is that random number generators all contain state which is updated with each invocation.

As such, having std::vector<std::future<std::vector<int>>>, with the RNG state passed as the argument in an asynchronous function call would result in a race condition. On the other hand, passing the state by value or const reference would result in the same generated value for all invocations.

I was thinking that at least, perhaps I could have used a std:future<std::vector<std::vector<int>>>; however, this still involves passing a reference to an asynchronous function call.

I should note that repeatability is not important to me in this case; as such, it doesn't matter to me what order the random numbers are generated. As long as the state of the random number generator can be protected against invalid states with a mutex, I am okay with such a solution.

Is there any way to use concurrency in such a case?


Aucun commentaire:

Enregistrer un commentaire