【问题标题】:simultaneously run different thread without waiting for other thread to complete同时运行不同的线程而不等待其他线程完成
【发布时间】:2016-12-04 07:31:25
【问题描述】:

问题是我想使用同时运行不同线程的 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循环(在每个线程上下文中)都将同时运行。我该如何做到这一点?如果你可以请分享一些示例代码,实际上我已经使用了 async 的未来,但我得到了与使用 join() 的正常 &lt;thread&gt; 相同的行为。

【问题讨论】:

    标签: c++ linux multithreading


    【解决方案1】:

    您遇到的问题是因为std::async 的相当愚蠢的定义(在我看来)它不必异步执行您的代码,而是可以在您尝试从它的@987654322 获取时运行它@返回值。

    没关系。如果将调用的第一个参数设置为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);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-21
      • 2013-03-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多