簡體   English   中英

如何使用多線程C ++循環啟動多個操作

[英]How to launch multiple operations in a loop using multithreading c++

介紹

我正在嘗試在6核機器上並行啟動4個功能: func1, func2, func3func4 每個函數將對填充向量實體進行1000次迭代。 主要功能是do_operations() 我在源代碼部分中發布了兩個版本的do_operations()


問題

通過使用第一個版本,我得到以下錯誤:

std::system_error'
what():  Resource temporarily unavailable

為了解決那個問題。 我在version 2添加了一個條件。 如果線程數等於6 ,這是我擁有的內核數。 然后,我運行線程並清除vector<thread> threads

我是否正確編寫線程功能? 我究竟做錯了什么。


源代碼

void my_class::func1(std::vector<std::string> & entities)
{
  for(int = 0; i < 1000;i++)
  {
      mtx.lock();
      entities.push_back(to_string(i));
      mtx.unlock();
  }
}

void my_class::func2(std::vector<std::string> & entities)
{
  for(int = 0; i < 1000;i++)
  {
      mtx.lock();
      entities.push_back(to_string(i));
      mtx.unlock();
  }
}


void my_class::func3(std::vector<std::string> & entities)
{
  for(int = 0; i < 1000;i++)
  {
      mtx.lock();
      entities.push_back(to_string(i));
      mtx.unlock();
  }
}

void my_class::func4(std::vector<std::string> & entities)
{  
  for(int = 0; i < 1000;i++)
  {
      mtx.lock();
      entities.push_back(to_string(i));
      mtx.unlock();
  }
}

版本1

void my_class::do_operations()
{
   //get number of CPUS 
   int concurentThreadsSupported = std::thread::hardware_concurrency();
   std::vector<std::thread> threads; 
   std::vector<std::string> entities;
    for(int i =0; i < 1000; i++)
    {
        threads.push_back(std::thread(&my_class::func1, this, ref(entities)));
        threads.push_back(std::thread(&my_class::func2, this, ref(entities)));
        threads.push_back(std::thread(&my_class::func3, this, ref(entities)));
        threads.push_back(std::thread(&my_class::func4, this, ref(entities)));
    }

    for(auto &t : threads){ t.join(); }
    threads.clear();
}

版本2

void my_class::do_operations()
{
   //get number of CPUS 
   int concurentThreadsSupported = std::thread::hardware_concurrency();
   std::vector<std::thread> threads; 
   std::vector<std::string> entities;
    for(int i =0; i < 1000; i++)
    {
        threads.push_back(std::thread(&my_class::func1, this, ref(entities)));
        threads.push_back(std::thread(&my_class::func2, this, ref(entities)));
        threads.push_back(std::thread(&my_class::func3, this, ref(entities)));
        threads.push_back(std::thread(&my_class::func4, this, ref(entities)));

          if((threads.size() == concurentThreadsSupported) || (i == 999))
          {
               for(auto &t : threads){ t.join(); }
              threads.clear();
          }
    }
}

您總共啟動了4000個線程。 如果每個線程獲得1MB的堆棧空間,則只有線程將占用4000MB的地址空間。 我的假設是您沒有為應用程序保留完整的4GB 32位地址空間(內核和硬件必須保留一些空間)。 我的第二個假設是,如果沒有足夠的空間分配新堆棧,它將返回您看到的消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM