信号量完全异常未得到处理 [英] semaphore full exception was unhandled

查看:111
本文介绍了信号量完全异常未得到处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello guys

我正在使用C#和VS 2010开发一个多线程应用程序但是我收到一个错误,信号量完全异常未处理向信号量添加指定的计数会导致它超过其最大数量。请看看它



Hello guys
I am developing a multi-threading application using C# and VS 2010 but I am getting a error that semaphore full exception was unhandled "adding the specified count to the semaphore would cause it to exceed its maximum count". Please have a look at it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using chickenFarm.Encrypt;
using System.Diagnostics;

namespace chickenFarm
{
    public delegate void priceCutter(Int32 pr);

    class EncoderDecoder
    {
        public string encode(OrderClass order)
        {
            //int id = order.getID();
            //int card = order.getCardNo();
           // int amt = order.getAmt();
            Console.WriteLine("Encoding the order {0}:{1}:{2}", order.getID(), order.getCardNo(), order.getAmt());
            return order.getID() + "6" + order.getCardNo() + "6" + order.getAmt() + "6";
            
        }

        public OrderClass decode(string order)
        {
            string[] Split = order.Split( '6' );
            OrderClass oc = new OrderClass();
            oc.setID(Int32.Parse(Split[0]));
            oc.setCardNo(Int32.Parse(Split[1]));
            oc.setAmt(Int32.Parse(Split[2]));
            Console.WriteLine("Decoding the order {0}:{1}:{2}", oc.getID(), oc.getCardNo(), oc.getAmt());
            return oc;
        }
    }//end EncoderDecoder

       class ChickenFarm
       {
           static Random r = new Random();
           Retailer retail;
           static MultiCellBuffer mcb;
           public static event priceCutter priceCut; // Define event
           private static int chickenPrice = 4;
           private static int p;

           public ChickenFarm()
           { }
          

           public ChickenFarm(Retailer r, MultiCellBuffer m)
           {
               retail = r;
               mcb = m;
               openFarm();
           }

           public int getPrice()
           {
               return chickenPrice;
           }

           public void openFarm()
           {
               retail.openFarm();
           }


           public void PricingModel()
           {
               Stopwatch watch = new Stopwatch(); // for time elapsed
               DateTime time = new DateTime();
               time = DateTime.Now;
               string format = "HH:mm:ss";

               Console.WriteLine("Chicken farm is open! Start time: " + time.ToString(format));
               watch.Start();
               int price;
               while (p <= 10)
               {
                   Thread.Sleep(2000); //price is updated every 2 seconds 
                   price = r.Next(4, 10);
                   Console.WriteLine("Current price is ${0:N}", chickenPrice);
                   changePrice(price);
               }
               watch.Stop();
               retail.openFarm();
               Thread.Sleep(3000);
               Console.WriteLine("The Chicken farm has closed! Elapsed time: {0}", watch.Elapsed);
               Console.WriteLine("Press any key to quit");
               Console.ReadLine();
           }

           public static void changePrice(int price)
           {
               if (price < chickenPrice)
               {
                   if (priceCut != null)
                   {
                       Console.WriteLine("\n******Price Cut!******\n");
                       priceCut(price); // emit event to subscribers
                       p++;
                   }
               }
               chickenPrice = price;
           }

           public string processOrder(int cell) //sends an order to the Order Processing class.
           {
               Encrypt.ServiceClient myClient = new Encrypt.ServiceClient();
               string ord;
               ord = mcb.getOneCell(cell);
               EncoderDecoder ed = new EncoderDecoder();
               OrderProcessing op = new OrderProcessing(ed.decode(ord), chickenPrice);

               Thread order = new Thread(new ThreadStart(op.process));
               order.Start();
               while (order.IsAlive)
               {
                   Thread.Sleep(50);
               }
               return op.printOrder();
           }

         /*  public priceCutter priceCutter
           {
               get
               {
                   throw new System.NotImplementedException();
               }
               set
               {
               }
           }

           internal MultiCellBuffer MultiCellBuffer
           {
               get
               {
                   throw new System.NotImplementedException();
               }
               set
               {
               }
           }

           internal OrderProcessing OrderProcessing
           {
               get
               {
                   throw new System.NotImplementedException();
               }
               set
               {
               }
           }

           internal EncoderDecoder EncoderDecoder
           {
               get
               {
                   throw new System.NotImplementedException();
               }
               set
               {
               }
           }

           internal Retailer Retailer
           {
               get
               {
                   throw new System.NotImplementedException();
               }
               set
               {
               }
           }
           */
       }

    
       class MultiCellBuffer
       {
           private int maxCells = 0;
           private string[] cells;
           private Semaphore sem;


           public MultiCellBuffer(int n)
           {
               maxCells = n;
               // Console.WriteLine("New Price is {0}", n);
               cells = new string[n];
               for (int i = 0; i < n; i++)
               {
                   cells[i] = "";
                   //Console.WriteLine("New Price is {0}", cells[i]);
               }
               sem = new Semaphore(n, n);
               // Console.WriteLine("New Price is {0}", sem);
           }

           public string setOneCell(string s)
           {
               sem.WaitOne();
               int cell = -1;
               string result;
               lock (cells) //locks cell array for empty cell searching
               {
                   for (int i = 0; i < maxCells; i++)
                   {
                       if (cells[i] == "")
                           cell = i;
                   }

                   if (cell != -1)
                   {
                       cells[cell] = s;
                   }
                   else
                   {
                       Console.WriteLine("Error. No empty cells found.");
                   }
               }
               ChickenFarm c = new ChickenFarm();
               result = c.processOrder(cell); //upon finding writing to a cell, the farm is called to get the order.
               cells[cell] = "";
               sem.Release(); // cell is emptied and made available
               return result;
           }

           public string getOneCell(int cellNo)
           {
               return cells[cellNo];
           }
       }

       class Retailer
       {
           bool farmOpen = false;
           static int threadCount, turnstile = 0;
           Random r = new Random();
           MultiCellBuffer mcb;
           Semaphore retailSem1, retailSem2;

           public Retailer(MultiCellBuffer m, int n)
           {
               //Console.WriteLine("New Price is {0}", n);
               mcb = m;
               threadCount = n;
               retailSem1 = new Semaphore(0, n);
               retailSem2 = new Semaphore(0, n);
           }

        /*   internal MultiCellBuffer MultiCellBuffer
           {
               get
               {
                   throw new System.NotImplementedException();
               }
               set
               {
               }
           }

           internal OrderClass OrderClass
           {
               get
               {
                   throw new System.NotImplementedException();
               }
               set
               {
               }
           }

          /* internal EncoderDecoder EncoderDecoder
           {
               get
               {
                   throw new System.NotImplementedException();
               }
               set
               {
               }
           }
           */
           
           public void startRetail()  //for starting retailer threads  
           {
               OrderClass order = new OrderClass(); //Each thread receives their own "Order Form"
               EncoderDecoder ed = new EncoderDecoder(); //Each thread receives its own Encoder, simulating an independent client-side operation
               int amt = r.Next(10, 50);
               string finalOrder, callback;
               DateTime time = new DateTime();
               string format = "HH:mm:ss";
               Stopwatch watch = new Stopwatch(); //uses a Stopwatch for elapsed time

               while (farmOpen == true)
               {
                   retailSem1.WaitOne(); ////////////////////////////////////////////////////////////////////////////////////////////
                   turnstile += 1;
                   if (turnstile == threadCount)
                   {
                       turnstile = 0;
                       retailSem2.Release(threadCount);//This block uses a double turnstile technique to prevent concurrency issues.
                   }                                   // Though it still seems to have issues every now and then...
                   retailSem2.WaitOne();/////////////////////////////////////////////////////////////////////////////////////////////

                   time = DateTime.Now;
                   watch.Start();
                   order.setID(Convert.ToInt32(Thread.CurrentThread.Name)); //create new order
                   order.setAmt(r.Next(10, 60));
                   order.setCardNo(r.Next(2000, 4000));

                   finalOrder = ed.encode(order); // encode order
                   time = DateTime.Now; // for timestamp
                   Console.WriteLine("Retailer {0} has placed an order for {1} chickens." + time.ToString(format), Thread.CurrentThread.Name, amt);
                   callback = mcb.setOneCell(finalOrder); // place order and receive confirmation.
                   watch.Stop();
                   Console.WriteLine(callback + "\n" + watch.Elapsed);
               }
           }

           public void chickenOnSale(int p)
           {  // Event handler
               Console.WriteLine("Chickens are on sale for ${0:N}.\n", p);
               retailSem1.Release(threadCount);

           }

           public void openFarm()
           {
               if (farmOpen == true)
                   farmOpen = false;
               else
                   farmOpen = true;
           }

       }//end Retailer

       class OrderClass
       {
           private int senderID, cardNo, amount;

           public void setID(int id)
           {
               senderID = id;
           }

           public int getID()
           {
               return senderID;
           }

           public void setCardNo(int num)
           {
               cardNo = num;
           }

           public int getCardNo()
           {
               return cardNo;
           }

           public void setAmt(int amt)
           {
               amount = amt;
           }

           public int getAmt()
           {
               return amount;
           }

           public string toString()
           {
               return ("Retailer: " + senderID + " Card Number: " + cardNo + " Amount: " + amount);
           }


       }//end OrderClass

       class OrderProcessing
       {
           private int amount, cardNo, ID, price;
           private double total, shipping = 5.99;
           private string OrderStatus = "Awaiting Processing";

           public OrderProcessing(OrderClass oc, int p)
           {
               amount = oc.getAmt();
               cardNo = oc.getCardNo();
               ID = oc.getID();
               price = p;
           }

           public void process()
           { //checks card number and calculates total price for the order. Sets confirmation string.
               if (checkCardNo())
               {
                   double tax = (amount * price) * .097;
                   total = (amount * price) + tax + shipping;
                   OrderStatus = ("Retailer " + ID + ": order processed. Total for " + amount + " chicken(s) at " + price.ToString("C") + " was " + total.ToString("C") + ".");
               }
               else
                   OrderStatus = ("Retailer" + ID + ": Order could not be processed. Invalid card number.");

           }

           public bool checkCardNo()
           {
               if (cardNo >= 2000 && cardNo <= 4000)
                   return true;
               else
                   return false;
           }

           public string printOrder()
           { //Sends confirmation string upon request.
               return OrderStatus;
           }
       }

      public class myApplication 
      {
          private const int retailerNum = 10; //Number of retailers
          private const int multiCellNum = 8;

     static void Main(string[] args) 
     {
         MultiCellBuffer mcb = new MultiCellBuffer(multiCellNum);//=4
         Retailer retail = new Retailer(mcb, retailerNum);//=(value from mcb,10)
         ChickenFarm chicken = new ChickenFarm(retail, mcb);

         ChickenFarm.priceCut += new priceCutter(retail.chickenOnSale);

         Thread farm = new Thread(new ThreadStart(chicken.PricingModel));
         farm.Start(); //Single farm thread. 

         Thread[] retailers = new Thread[retailerNum];
         for (int i = 0; i < retailerNum; i++)
         {   // Start N retailer threads
             retailers[i] = new Thread(new ThreadStart(retail.startRetail));
             retailers[i].Name = (i + 1).ToString();
             retailers[i].Start();
         }
     }
  }

}





我试了很多解决方法,但我想我无法弄清楚。谢谢提前



I tried many ways to solve it but I think i cant figure it out.Thanks in advance

推荐答案

{0:N},chickenPrice);
changePrice(price);
}
watch.Stop();
retail.openFarm();
Thread.Sleep( 3000 );
Console.WriteLine( 鸡场关闭了!经过的时间:{0 },watch.Elapsed);
Console.WriteLine( 按任意键退出);
Console.ReadLine();
}

public static void changePrice( int price)
{
if (price < chickenPrice)
{
if (priceCut!= null
{
Console.WriteLine( \ n ******降价!****** \ N);
priceCut(价格); // 向订阅者发送事件
p ++;
}
}
chickenPrice =价格;
}

public string processOrder(int cell) //sends an order to the Order Processing class.
{
Encrypt.ServiceClient myClient = new Encrypt.ServiceClient();
string ord;
ord = mcb.getOneCell(cell);
EncoderDecoder ed = new EncoderDecoder();
OrderProcessing op = new OrderProcessing(ed.decode(ord), chickenPrice);

Thread order = new Thread(new ThreadStart(op.process));
order.Start();
while (order.IsAlive)
{
Thread.Sleep(50);
}
return op.printOrder();
}

/* public priceCutter priceCutter
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}

internal MultiCellBuffer MultiCellBuffer
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}

internal OrderProcessing OrderProcessing
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}

internal EncoderDecoder EncoderDecoder
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}

internal Retailer Retailer
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
*/

}


class MultiCellBuffer
{
private int maxCells = 0;
private string[] cells;
private Semaphore sem;


public MultiCellBuffer(int n)
{
maxCells = n;
// Console.WriteLine(\"New Price is {0}\", n);
cells = new string[n];
for (int i = 0; i < n; i++)
{
cells[i] = \"\";
//Console.WriteLine(\"New Price is {0}\", cells[i]);
}
sem = new Semaphore(n, n);
// Console.WriteLine(\"New Price is {0}\", sem);
}

public string setOneCell(string s)
{
sem.WaitOne();
int cell = -1;
string result;
lock (cells) //locks cell array for empty cell searching
{
for (int i = 0; i < maxCells; i++)
{
if (cells[i] == \"\")
cell = i;
}

if (cell != -1)
{
cells[cell] = s;
}
else
{
Console.WriteLine(\"Error. No empty cells found.\");
}
}
ChickenFarm c = new ChickenFarm();
result = c.processOrder(cell); //upon finding writing to a cell, the farm is called to get the order.
cells[cell] = \"\";
sem.Release(); // cell is emptied and made available
return result;
}

public string getOneCell(int cellNo)
{
return cells[cellNo];
}
}

class Retailer
{
bool farmOpen = false;
static int threadCount, turnstile = 0;
Random r = new Random();
MultiCellBuffer mcb;
Semaphore retailSem1, retailSem2;

public Retailer(MultiCellBuffer m, int n)
{
//Console.WriteLine(\"New Price is {0}\", n);
mcb = m;
threadCount = n;
retailSem1 = new Semaphore(0, n);
retailSem2 = new Semaphore(0, n);
}

/* internal MultiCellBuffer MultiCellBuffer
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}

internal OrderClass OrderClass
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}

/* internal EncoderDecoder EncoderDecoder
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
*/


public void startRetail() //for starting retailer threads
{
OrderClass order = new OrderClass(); //Each thread receives their own \"Order Form\"
EncoderDecoder ed = new EncoderDecoder(); //Each thread receives its own Encoder, simulating an independent client-side operation
int amt = r.Next(10, 50);
string finalOrder, callback;
DateTime time = new DateTime();
string format = \"HH:mm:ss\";
Stopwatch watch = new Stopwatch(); //uses a Stopwatch for elapsed time

while (farmOpen == true)
{
retailSem1.WaitOne(); ////////////////////////////////////////////////////////////////////////////////////////////
turnstile += 1;
if (turnstile == threadCount)
{
turnstile = 0;
retailSem2.Release(threadCount);//This block uses a double turnstile technique to prevent concurrency issues.
} // Though it still seems to have issues every now and then...
retailSem2.WaitOne();/////////////////////////////////////////////////////////////////////////////////////////////

time = DateTime.Now;
watch.Start();
order.setID(Convert.ToInt32(Thread.CurrentThread.Name)); //create new order
order.setAmt(r.Next(10, 60));
order.setCardNo(r.Next(2000, 4000));

finalOrder = ed.encode(order); // encode order
time = DateTime.Now; // for timestamp
Console.WriteLine(\"Retailer {0} has placed an order for {1} chickens.\" + time.ToString(format), Thread.CurrentThread.Name, amt);
callback = mcb.setOneCell(finalOrder); // place order and receive confirmation.
watch.Stop();
Console.WriteLine(callback + \"\n\" + watch.Elapsed);
}
}

public void chickenOnSale(int p)
{ // Event handler
Console.WriteLine(\"Chickens are on sale for
{0:N}", chickenPrice); changePrice(price); } watch.Stop(); retail.openFarm(); Thread.Sleep(3000); Console.WriteLine("The Chicken farm has closed! Elapsed time: {0}", watch.Elapsed); Console.WriteLine("Press any key to quit"); Console.ReadLine(); } public static void changePrice(int price) { if (price < chickenPrice) { if (priceCut != null) { Console.WriteLine("\n******Price Cut!******\n"); priceCut(price); // emit event to subscribers p++; } } chickenPrice = price; } public string processOrder(int cell) //sends an order to the Order Processing class. { Encrypt.ServiceClient myClient = new Encrypt.ServiceClient(); string ord; ord = mcb.getOneCell(cell); EncoderDecoder ed = new EncoderDecoder(); OrderProcessing op = new OrderProcessing(ed.decode(ord), chickenPrice); Thread order = new Thread(new ThreadStart(op.process)); order.Start(); while (order.IsAlive) { Thread.Sleep(50); } return op.printOrder(); } /* public priceCutter priceCutter { get { throw new System.NotImplementedException(); } set { } } internal MultiCellBuffer MultiCellBuffer { get { throw new System.NotImplementedException(); } set { } } internal OrderProcessing OrderProcessing { get { throw new System.NotImplementedException(); } set { } } internal EncoderDecoder EncoderDecoder { get { throw new System.NotImplementedException(); } set { } } internal Retailer Retailer { get { throw new System.NotImplementedException(); } set { } } */ } class MultiCellBuffer { private int maxCells = 0; private string[] cells; private Semaphore sem; public MultiCellBuffer(int n) { maxCells = n; // Console.WriteLine("New Price is {0}", n); cells = new string[n]; for (int i = 0; i < n; i++) { cells[i] = ""; //Console.WriteLine("New Price is {0}", cells[i]); } sem = new Semaphore(n, n); // Console.WriteLine("New Price is {0}", sem); } public string setOneCell(string s) { sem.WaitOne(); int cell = -1; string result; lock (cells) //locks cell array for empty cell searching { for (int i = 0; i < maxCells; i++) { if (cells[i] == "") cell = i; } if (cell != -1) { cells[cell] = s; } else { Console.WriteLine("Error. No empty cells found."); } } ChickenFarm c = new ChickenFarm(); result = c.processOrder(cell); //upon finding writing to a cell, the farm is called to get the order. cells[cell] = ""; sem.Release(); // cell is emptied and made available return result; } public string getOneCell(int cellNo) { return cells[cellNo]; } } class Retailer { bool farmOpen = false; static int threadCount, turnstile = 0; Random r = new Random(); MultiCellBuffer mcb; Semaphore retailSem1, retailSem2; public Retailer(MultiCellBuffer m, int n) { //Console.WriteLine("New Price is {0}", n); mcb = m; threadCount = n; retailSem1 = new Semaphore(0, n); retailSem2 = new Semaphore(0, n); } /* internal MultiCellBuffer MultiCellBuffer { get { throw new System.NotImplementedException(); } set { } } internal OrderClass OrderClass { get { throw new System.NotImplementedException(); } set { } } /* internal EncoderDecoder EncoderDecoder { get { throw new System.NotImplementedException(); } set { } } */ public void startRetail() //for starting retailer threads { OrderClass order = new OrderClass(); //Each thread receives their own "Order Form" EncoderDecoder ed = new EncoderDecoder(); //Each thread receives its own Encoder, simulating an independent client-side operation int amt = r.Next(10, 50); string finalOrder, callback; DateTime time = new DateTime(); string format = "HH:mm:ss"; Stopwatch watch = new Stopwatch(); //uses a Stopwatch for elapsed time while (farmOpen == true) { retailSem1.WaitOne(); //////////////////////////////////////////////////////////////////////////////////////////// turnstile += 1; if (turnstile == threadCount) { turnstile = 0; retailSem2.Release(threadCount);//This block uses a double turnstile technique to prevent concurrency issues. } // Though it still seems to have issues every now and then... retailSem2.WaitOne();///////////////////////////////////////////////////////////////////////////////////////////// time = DateTime.Now; watch.Start(); order.setID(Convert.ToInt32(Thread.CurrentThread.Name)); //create new order order.setAmt(r.Next(10, 60)); order.setCardNo(r.Next(2000, 4000)); finalOrder = ed.encode(order); // encode order time = DateTime.Now; // for timestamp Console.WriteLine("Retailer {0} has placed an order for {1} chickens." + time.ToString(format), Thread.CurrentThread.Name, amt); callback = mcb.setOneCell(finalOrder); // place order and receive confirmation. watch.Stop(); Console.WriteLine(callback + "\n" + watch.Elapsed); } } public void chickenOnSale(int p) { // Event handler Console.WriteLine("Chickens are on sale for


{0:N}.\n\", p);
retailSem1.Release(threadCount);

}

public void openFarm()
{
if (farmOpen == true)
farmOpen = false;
else
farmOpen = true;
}

}//end Retailer

class OrderClass
{
private int senderID, cardNo, amount;

public void setID(int id)
{
senderID = id;
}

public int getID()
{
return senderID;
}

public void setCardNo(int num)
{
cardNo = num;
}

public int getCardNo()
{
return cardNo;
}

public void setAmt(int amt)
{
amount = amt;
}

public int getAmt()
{
return amount;
}

public string toString()
{
return (\"Retailer: \" + senderID + \" Card Number: \" + cardNo + \" Amount: \" + amount);
}


}//end OrderClass

class OrderProcessing
{
private int amount, cardNo, ID, price;
private double total, shipping = 5.99;
private string OrderStatus = \"Awaiting Processing\";

public OrderProcessing(OrderClass oc, int p)
{
amount = oc.getAmt();
cardNo = oc.getCardNo();
ID = oc.getID();
price = p;
}

public void process()
{ //checks card number and calculates total price for the order. Sets confirmation string.
if (checkCardNo())
{
double tax = (amount * price) * .097;
total = (amount * price) + tax + shipping;
OrderStatus = (\"Retailer \" + ID + \": order processed. Total for \" + amount + \" chicken(s) at \" + price.ToString(\"C\") + \" was \" + total.ToString(\"C\") + \".\");
}
else
OrderStatus = (\"Retailer\" + ID + \": Order could not be processed. Invalid card number.\");

}

public bool checkCardNo()
{
if (cardNo >= 2000 && cardNo <= 4000)
return true;
else
return false;
}

public string printOrder()
{ //Sends confirmation string upon request.
return OrderStatus;
}
}

public class myApplication
{
private const int retailerNum = 10; //Number of retailers
private const int multiCellNum = 8;

static void Main(string[] args)
{
MultiCellBuffer mcb = new MultiCellBuffer(multiCellNum);//=4
Retailer retail = new Retailer(mcb, retailerNum);//=(value from mcb,10)
ChickenFarm chicken = new ChickenFarm(retail, mcb);

ChickenFarm.priceCut += new priceCutter(retail.chickenOnSale);

Thread farm = new Thread(new ThreadStart(chicken.PricingModel));
farm.Start(); //Single farm thread.

Thread[] retailers = new Thread[retailerNum];
for (int i = 0; i < retailerNum; i++)
{ // Start N retailer threads
retailers[i] = new Thread(new ThreadStart(retail.startRetail));
retailers[i].Name = (i + 1).ToString();
retailers[i].Start();
}
}
}

}
{0:N}.\n", p); retailSem1.Release(threadCount); } public void openFarm() { if (farmOpen == true) farmOpen = false; else farmOpen = true; } }//end Retailer class OrderClass { private int senderID, cardNo, amount; public void setID(int id) { senderID = id; } public int getID() { return senderID; } public void setCardNo(int num) { cardNo = num; } public int getCardNo() { return cardNo; } public void setAmt(int amt) { amount = amt; } public int getAmt() { return amount; } public string toString() { return ("Retailer: " + senderID + " Card Number: " + cardNo + " Amount: " + amount); } }//end OrderClass class OrderProcessing { private int amount, cardNo, ID, price; private double total, shipping = 5.99; private string OrderStatus = "Awaiting Processing"; public OrderProcessing(OrderClass oc, int p) { amount = oc.getAmt(); cardNo = oc.getCardNo(); ID = oc.getID(); price = p; } public void process() { //checks card number and calculates total price for the order. Sets confirmation string. if (checkCardNo()) { double tax = (amount * price) * .097; total = (amount * price) + tax + shipping; OrderStatus = ("Retailer " + ID + ": order processed. Total for " + amount + " chicken(s) at " + price.ToString("C") + " was " + total.ToString("C") + "."); } else OrderStatus = ("Retailer" + ID + ": Order could not be processed. Invalid card number."); } public bool checkCardNo() { if (cardNo >= 2000 && cardNo <= 4000) return true; else return false; } public string printOrder() { //Sends confirmation string upon request. return OrderStatus; } } public class myApplication { private const int retailerNum = 10; //Number of retailers private const int multiCellNum = 8; static void Main(string[] args) { MultiCellBuffer mcb = new MultiCellBuffer(multiCellNum);//=4 Retailer retail = new Retailer(mcb, retailerNum);//=(value from mcb,10) ChickenFarm chicken = new ChickenFarm(retail, mcb); ChickenFarm.priceCut += new priceCutter(retail.chickenOnSale); Thread farm = new Thread(new ThreadStart(chicken.PricingModel)); farm.Start(); //Single farm thread. Thread[] retailers = new Thread[retailerNum]; for (int i = 0; i < retailerNum; i++) { // Start N retailer threads retailers[i] = new Thread(new ThreadStart(retail.startRetail)); retailers[i].Name = (i + 1).ToString(); retailers[i].Start(); } } } }





I tried many ways to solve it but I think i cant figure it out.Thanks in advance



I tried many ways to solve it but I think i cant figure it out.Thanks in advance


This is not a good question, just because you just show a code dump, not explaining anything. Normally, you need to explain the goals of your work first and provide not the real code, but some simple code focusing only on the problem you are looking for help about. If the behavior of your code does not match what you expected, use the debugger and fix it. If you failed to do so, describe what did you want to achieve, what’s expected behavior, what is observed behavior, why do you feel it’s wrong. If you have some exceptions, describe steps to reproduce, complete exception information. Comment the points in code related to exception throwing/propagation. Post all what’s relevant. See also: http://www.sscce.org.



At the same time, the fair rules of code reviews and providing some help allows to read it until the first big problem is encountered. I tried to scan your code with my eyes until I stopped on these two fragments of the code:

This is not a good question, just because you just show a code dump, not explaining anything. Normally, you need to explain the goals of your work first and provide not the real code, but some simple code focusing only on the problem you are looking for help about. If the behavior of your code does not match what you expected, use the debugger and fix it. If you failed to do so, describe what did you want to achieve, what's expected behavior, what is observed behavior, why do you feel it's wrong. If you have some exceptions, describe steps to reproduce, complete exception information. Comment the points in code related to exception throwing/propagation. Post all what's relevant. See also: http://www.sscce.org.

At the same time, the fair rules of code reviews and providing some help allows to read it until the first big problem is encountered. I tried to scan your code with my eyes until I stopped on these two fragments of the code:
while (order.IsAlive)
{
    Thread.Sleep(50);
}

and

and

while (p <= 10)
    {
        Thread.Sleep(2000);
        //...
    }



Both pieces are related to something called \"spin wait\", which is a really bad thing. And tells me, that, despite of using the semaphores somewhere else, are not really using threading and thread synchronization at all. These fragment of code makes further reading useless: they already tells me that your general design of code is wrong and is not worth considering.



I cannot tell you what would you need to do instead, because you never explained the purpose of these fragments, and pretty much nothing about your code at all. Let me tell you one key consideration. Let’s say, you write Thread.Sleep(50). My question would be: why not 51? I am sure you cannot provide satisfactory answer. It means that the whole idea is wrong. This is not how multithreading is applied for solving application problems.



—SA


Both pieces are related to something called "spin wait", which is a really bad thing. And tells me, that, despite of using the semaphores somewhere else, are not really using threading and thread synchronization at all. These fragment of code makes further reading useless: they already tells me that your general design of code is wrong and is not worth considering.

I cannot tell you what would you need to do instead, because you never explained the purpose of these fragments, and pretty much nothing about your code at all. Let me tell you one key consideration. Let's say, you write Thread.Sleep(50). My question would be: why not 51? I am sure you cannot provide satisfactory answer. It means that the whole idea is wrong. This is not how multithreading is applied for solving application problems.

—SA


这篇关于信号量完全异常未得到处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆