多线程生产者使用者设计模式的内存/CPU问题 [英] Memory/CPU Issues With Multithread Producer Consumer Design Pattern

查看:74
本文介绍了多线程生产者使用者设计模式的内存/CPU问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚为什么内存一直保持每秒增长,为什么我的cpu使用率如此之高(90%)...

我建立了一个多线程数据库,该数据库实现了Producer Consumer设计模式.我要提取实时股票市场数据,然后对其进行解析,然后更新数据库中的表.这是我正在做的事的一个例子:

I can''t figure why memory is keeps growing by the second and why my cpu usage is so high (90%)...

I building a multithreaded database that''s implementing the Producer Consumer design pattern. I''m pulling in real-time stock market data which I''m parsing then updating a table in my database. Here''s an example of what I''m doing:

List<threads> threads = new List<threads>();
object sync = new object();
EventWaitHandle ewh = AutoResetEvent(false);
Queue<string> q =  new Queue<string>();
int numberOfThreads = Environment.ProcessorCount;

// constructor of class used for parsing data
public ParseCls()
{
  MyDatabase databaseObj = new MyDatabase();
  for(int i = 0; i < numberOfThreads; i++)
  {
     threads.Add(new Thread(prase));
     threads[i].Start();
  }
}
public GetData(string stockData)
{
  lock(sync)
  {
     q.Enqueue(stockData);
  }
  ewh.Set();
}

private void parse()
{
  string s = "";
  lock(sync)
 {
   string s = q.Dequeue();
 }

 if(s.Length != "")
 {
   // parse string and create a new one then pass results to
   // my database
   string newS = s.Substring(0,1);
   dataBaseObj.GetData(newS);
 }
 else
 {
   ewh.WaitOne();
   s = "";
 }
 
// here's my database class
class MyDatabase
{
  int numberOfThreads = Enviorment.ProcessorCount;
  List<threads> threads = new List<threads>();
  EventWaitHandle ewh = AutoResetEvent(false);
  object sync = new object();
  Queue<string> q = new Queue<string>();

  public MyDatabase()
  {
     for(int i = 0; i < numberOfThreads; i++)
     {
        threads.Add(new Thread(update));
        threads[i].Start();
     }
  }

  public void GetData(string data)
  {
    lock(sync)
    {
      q.Enqueue(data);
    }
    ewh.Set();
  }

  private void update()
  {
    SQLConnection conn = etc...
    // other ado.net objects...

    while(true)
    {
      lock(sync)
      {
        string s = q.Dequeue();
      }

      // update database here
      // code...
      if(etc...)
      // blah, blah, blah
      else
      {
       ewh.WaitOne();
      }
    }
  }
}

推荐答案

这会占用处理器时间,因为您的更新方法在循环并尝试执行之前没有任何延迟处理下一个值.它只是保持循环.

它一直在消耗内存,因为您创建的线程永远不会运行,因此它们永远不会被处置/取消分配.
It''s taking processor time because your update method doesn''t have any kind of delay built in before it cycles and tries to handle the next value. It just keeps cycling.

It keeps eating memory because you''re creating threads that never get disposed/deallocated because they''re running endlessly.


这篇关于多线程生产者使用者设计模式的内存/CPU问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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