vendredi 3 avril 2020

C# enque random int

I have three threads which are supposed to add a random int to a queue, a fourth that dequeues an int, and a fifth that prints the numbers within it. I'm using threads because they will eventually be needed for the scope of this program and to enqueue/dequeue far more numbers, but having issues with generating a random int. I'm using a class RandomGenerator to create the number, and creating an instance of this class then invoking its GetRandom method to set an int field to a random number. I'm then passing this field into the first three threads which invoke the method to enqueue. The int that prints is not random and I realize this is because I'm simply calling the method at the beginning of the program and passing the same exact number to all three threads. I'm relatively new to C# and realize I may be making a basic mistake. I also realize the fourth thread sometimes accesses the queue when it's empty but isn't as important at the moment. Here is the code:

...

class Program
{
    static void Main()
    {
        Program p = new Program();
        RandomGenerator rg = new RandomGenerator();

        Queue<int> numberQueue = new Queue<int>();

        int randomNumber = rg.GetRandom(1, 10);

        Thread T1 = new Thread(delegate () { p.EnqueueNumber(numberQueue, randomNumber); });
        Thread T2 = new Thread(delegate () { p.EnqueueNumber(numberQueue, randomNumber); });
        Thread T3 = new Thread(delegate () { p.EnqueueNumber(numberQueue, randomNumber); });
        Thread T4 = new Thread(delegate () { p.DequeueNumber(numberQueue); });
        Thread T5 = new Thread(delegate () { p.PrintNumbers(numberQueue); });

        T1.Start();
        T2.Start();
        T3.Start();
        T4.Start();
        T5.Start();

        T1.Join();
        T2.Join();
        T3.Join();
        T4.Join();
        T5.Join();
    }

    public void EnqueueNumber(Queue<int> numberQueue, int randomNumber)
    {
        numberQueue.Enqueue(randomNumber);
    }

    public void DequeueNumber(Queue<int> numberQueue)
    {
        int randomNumber = 
        numberQueue.Dequeue();
    }

    public void PrintNumbers(Queue<int> numberQueue)
    {
        foreach (int i in numberQueue)
        {
            Console.Write(i);
        }

        Console.ReadKey();
    }
}

public class RandomGenerator
{
    private static Random _random = new Random();
    private static object syncLock = new object();

    public int GetRandom(int min, int max)
    {
        lock (syncLock)
        {
            return _random.Next(min, max);
        }
    }
}

...




Aucun commentaire:

Enregistrer un commentaire