介绍
我正在尝试并行启动 4 个函数:func1, func2, func3
和 func4
在 6
上芯机。每个函数将迭代 1000 次填充 vector 实体。主要功能是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 位地址空间(必须为内核和硬件保留一些空间)。我的第二个假设是,如果没有足够的空间来分配新堆栈,它将返回您看到的消息。
关于c++ - 如何使用多线程 C++ 在循环中启动多个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35149485/