lundi 23 mai 2016

Spawn continous threads depending on a thread value

I need help coming up with a solution for some real code I want to base this on.

Problem Description

Let's say there was a class RandomNumberGenerator.

Imagine RandomNumberGenerator.generate() that generated numbers from 0 to 10.

Then let's create a loop that passes RandomNumberGenerator to a thread for the thread to create a random number.

The loop would stop when one of those threads hits lets say 0.

Pseudocode

void thread(RandomNumberGenerator & RNG)
{
    int randomNumber = RNG.generate();
    if(randomNumber == 0) {
        //Update magicNumber to true
        //to stop the loop and stop creating any more threads.
    } else {
        //Collect every number generated that is not 0.
    }
}

void main() {
    bool magicNumber = false;
    RandomNumberGenerator RNG(0, 10);

    while(magicNumber == false) {
        std::thread(&thread, RNG);
    }

    //cout number collection
    return 0;
}

Is it possible to collect the numbers created by those threads?

I'm familiar with basic threading with <mutex> and <thread> based on data known and measured beforehand but not data that is not known yet.

That plus I can't get my head around the scoping of all this.

I would really like to write real code based on this example. I'd really appreciate some guidance on this one.

Aucun commentaire:

Enregistrer un commentaire