问题是我想使用 C++ 库,它同时运行不同的线程,而无需其他线程等待,直到前一个线程完成并且每个线程中的功能同时运行,我正在谈论要在线程中运行的代码;示例代码如下所示。
while(condition is true<it is infinite loop >){
running sleep here with random time
sleep(random time(sec))
rest of the code is here
}
这个无限while
循环在每个线程中运行。我想在每个线程中运行这个 while 循环,以便同时运行,而不会卡在第一个要完成的线程上。换句话说,所有无限 while 循环(在每个线程上下文中)都将同时运行。我该如何实现这一目标?如果您可以的话,请分享一些示例代码,实际上我已经将 future 与异步一起使用,但我得到了与正常情况相同的行为 <thread>
使用join()
.
最佳答案
您遇到的问题是因为 std::async
的定义相当愚蠢(在我看来),它不必异步执行您的代码,而是可以在您尝试从其 std::future
返回值获取时运行它。
没关系。如果将调用的第一个参数设置为 std::launch::async
,则会强制它异步运行。然后,您可以将 future 保存在容器中,如果您定期从该容器中退出 future,则可以运行系统允许的任意数量的线程。
这是一个例子:
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
#include <vector>
#include <mutex>
using future_store = std::vector<std::future<void>>;
void retireCompletedThreads(future_store &threadList)
{
for (auto i = threadList.begin(); i != threadList.end(); /* ++i */)
{
if (i->wait_for(std::chrono::seconds(0)) == std::future_status::ready)
{
i->get();
i = threadList.erase(i);
}
else
{
++i;
}
}
}
void waitForAllThreads(future_store &threadList)
{
for (auto& f : threadList)
{
f.get();
}
}
std::mutex coutMutex;
int main(int argc, char* argv[])
{
future_store threadList;
// No infinite loop here, but you can if you want.
// You do need to limit the number of threads you create in some way though,
// for example, only create new threads if threadList.size() < 20.
for (auto i = 0; i < 20; ++i)
{
auto f = std::async(std::launch::async,
[i]() {
{
std::lock_guard<std::mutex> l(coutMutex);
std::cout << "Thread " << i << " started" << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> l(coutMutex);
std::cout << "Thread " << i << " completed" << std::endl;
}
});
threadList.push_back(std::move(f));
// Existing threads need to be checked for completion every so often
retireCompletedThreads(threadList);
}
waitForAllThreads(threadList);
}
关于c++ - 同时运行不同的线程,无需等待其他线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40956456/