Ejemplo n.º 1
0
        /// <summary>
        /// Farms some chickens.
        /// </summary>
        public void FarmSomeChickens()
        {
            CancellationToken token = cancelSource.Token;
            timeFarmStarted = DateTime.UtcNow;
            UpdatePrice();
            var multiCellBuffer = new MultiCellBuffer(token);

            while (!token.IsCancellationRequested)
            {
                try
                {
                    string newOrderEncoded;
                    if (multiCellBuffer.GetOneCell(out newOrderEncoded))
                    {
                        var newOrder = OrderClass.Decode(newOrderEncoded);
                        averageNumberOfChickens = (newOrder.Amount + averageNumberOfChickens) / 2.0;
                        timeLastOrdered = DateTime.UtcNow;
                        var orderProcessing = new OrderProcessing(newOrder, GetPrice());
                        var OrderProcessingThread = new Thread(orderProcessing.ProcessOrder) { Name = "OrderProcessing" + newOrder.SenderId };
                        OrderProcessingThread.Start();
                    }
                    UpdatePrice();
                }
                catch (OperationCanceledException e)
                {
                    Debug.WriteLine("A cancellation for {0} is requested.", Thread.CurrentThread.Name);
                }
            }
            Console.WriteLine("Total Time: {0} ms", (DateTime.UtcNow - timeFarmStarted).Milliseconds);
        }
Ejemplo n.º 2
0
        public static bool parkThreadRunning = true;    // boolean variable to keep track of whether or not our parkThread is running


        /*
         *  Main program to simulate our Ticket Agencies making orders from our Park
         */
        static void Main(string[] args)
        {
            Park           park         = new Park();                       // instantiate a Park object named park
            TicketAgencies ticketAgency = new TicketAgencies();             // instantiate a TicketAgencies object named ticketAgency

            MCB = new MultiCellBuffer(3);                                   // instantiate our MCB with 3 cells per assignment req.

            Thread parkThread = new Thread(new ThreadStart(park.parkCtor)); // create our parkThread with our park Ctor


            parkThread.Start();                                                             // start the park Thread

            Park.priceCut += new priceCutEvent(ticketAgency.ticketSale);                    // use event handler when a priceCut (ticketSale) occurs

            Park.priceChange += new priceChangeEvent(ticketAgency.ticketIncrease);          // use event handler when a price increase occurs

            TicketAgencies.newPO += new newPO_Event(park.processPO);                        // process our order once a newPO event is emitted

            OrderProcessing.PO_Processed += new processPO_Event(ticketAgency.PO_Processed); // callback for when order is processed

            ticketAgencies = new Thread[5];                                                 // [per project requirements . . . for loop to create 5 ticketAgency threads]

            // in our for loop we create a new thread using our ticketAgency ctor and we set the name (senderId)
            // for each ticket agency with numbers 1 - 5. We then start each thread.
            for (int i = 0; i < 5; i++)
            {
                ticketAgencies[i]      = new Thread(new ThreadStart(ticketAgency.ticketAgency));
                ticketAgencies[i].Name = (i + 1).ToString();

                ticketAgencies[i].Start();
            }
        }
Ejemplo n.º 3
0
 public BookStore(MultiCellBuffer buffer)
 {
     this.buffer      = buffer;
     this.random      = new Random();
     this.calendar    = new Calendar();
     this.total_books = Convert.ToInt32((calendar.Base_Price(calendar.Day())).Item3);
 }
Ejemplo n.º 4
0
 // Constructor that gets all the stuff
 public Publisher(MultiCellBuffer buffer, int publisherId)
 {
     this.buffer      = buffer;
     this.publisherId = publisherId;
     base_price       = (c.Base_Price(c.Day())).Item1;
     past_price       = base_price;
     discount         = (c.Base_Price(c.Day()).Item2);
     this.random      = new Random();
 }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            //  Buffer between server and client
            MultiCellBuffer buffer = new MultiCellBuffer(3);

            ChickenFarm c = new ChickenFarm(buffer);                   //  Give buffer and P value (optional) to server program
            Retailer    r = new Retailer(c.getSessionToken(), buffer); //  Give server session token and buffer to client program


            c.priceCut    += new priceCutEvent(r.UpdatePrice);
            r.orderPlaced += new orderPlacedEvent(c.ProcessOrder);
            OrderProcessing.processingDone += new orderProcessedEvent(r.OrderProcessed);

            //  Start Threads
            r.StartRetailers(5);
            c.StartServer();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Runs the store to send orders to the chicken farm.
        /// </summary>
        public void RunStore()
        {
            var orderTimes = new List<long>();
            var baseChickens = Thread.CurrentThread.ManagedThreadId * 23;
            var chickenDemand = Thread.CurrentThread.ManagedThreadId * 7 / 2;
            // Loop until stop is requested
            while (!token.IsCancellationRequested)
            {
                WaitHandle.WaitAny(new[] { priceCutManualResetEvent, token.WaitHandle });
                if (!token.IsCancellationRequested) //did cancellation wake us?
                {
                    int numChickens;
                    lock (syncRoot)
                    {
                        // Determine what to order based on price and demand.
                        numChickens = baseChickens - chickenDemand * (int)(chickenPrice);
                    }

                    // Put in order for chickens
                    if (numChickens > 0)
                    {
                        int ccNumber = Math.Min(7000, 5000 + Thread.CurrentThread.ManagedThreadId + numChickens);
                        var OrderObject = new OrderClass
                                              {
                                                  Amount = numChickens,
                                                  SenderId = Thread.CurrentThread.Name,
                                                  CardNo = ccNumber
                                              };
                        //sends order to encoder
                        string encoded = OrderObject.Encode();
                        timeSent = DateTime.UtcNow;
                        //send encoded string to free cell in multiCellBuffer
                        var cell = new MultiCellBuffer(token);
                        try
                        {
                            cell.SetOneCell(encoded);

                            // Wait for order confirmation
                            var eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset,
                                                                      Thread.CurrentThread.Name);
                            WaitHandle.WaitAny(new[] { eventWaitHandle, token.WaitHandle });

                            DateTime timeReceive = DateTime.UtcNow;
                            TimeSpan elapsedTime = timeReceive - timeSent;

                            Console.WriteLine("The order for {0} took {1} ms.", Thread.CurrentThread.Name,
                                              elapsedTime.Milliseconds);
                            orderTimes.Add(elapsedTime.Milliseconds);
                        }
                        catch (OperationCanceledException e)
                        {
                            Debug.WriteLine("A cancellation for {0} is requested.", Thread.CurrentThread.Name);
                        }
                    }
                }
            }
            double averageOrderTime = orderTimes.Count == 0 ? 0.0 : orderTimes.Average();
            Console.WriteLine("{0}: ARTOC: {1} ms", Thread.CurrentThread.Name, averageOrderTime);
        }