【问题标题】:std threads with specific timeout具有特定超时的 std 线程
【发布时间】:2015-08-01 06:28:20
【问题描述】:

目前我启动我的线程并等待它完成:

void ClassA::StartTest() // btn click from GUI
{
    ClassB classB;

    std::vector<std::thread> threads;
    for(int counter=0; counter<4; counter++)
    {
        threads.at(counter) = std::thread(&ClassB::ExecuteTest, classB);
        // if I join the threads here -> no parallelism
    }

    // wait for threads to finish
    for(auto it=threads.begin(); it!=threads.end(); it++)
        it->join();
}

B 类

#include <mutex>

ClassB
{
public:
    void ExecuteTest(); // thread function
private:
    std::mutex m_mutex;
    bool ExecuteOtherWork(std::string &value);
};

相关方法ExecuteTest()

void ClassB::ExecuteTest()
{
    std::string tmp;

    std::lock_guard<std::mutex> lock(m_mutex); // lock mutex
    std::stringstream stream(pathToFile);

    while(getline(stream, tmp, ',')) // read some comma sep stuff 
    {
        if(!ExecuteOtherWork(tmp)) break;
    }
}

一切正常,但我想要线程超时:假设 40 秒后线程必须退出那里工作并返回主线程。 我该怎么做?

谢谢!

【问题讨论】:

  • Getline 和它的流式处理不能很好地超时,并且杀死线程将使互斥锁保持锁定状态。有什么方法可以将终止消息写入流中?

标签: c++ c++11 visual-studio-2012 std stdthread


【解决方案1】:

在while循环中添加超时检查:

std::chrono::time_point<std::chrono::steady_clock> start(std::chrono::steady_clock::now());
std::chrono::seconds timeout(timeoutinSec);
while(getline(stream, tmp, ',') && std::chrono::steady_clock::now() - start < timeout) // read some comma sep stuff 
{
    if(!ExecuteOtherWork(tmp)) break;
}

如果 ExecuteOtherWork() 是一个快速操作,那么您可以每执行 X 次循环检查一次时间。

【讨论】:

  • 不错的解决方案,但它不会从阻塞的 getline 调用中退出。
  • 也许应该将阻塞的 getline 调用移至单独的线程。 “计时”线程不应阻塞。除非 getline 提供的 API 只能阻塞一段时间,否则应该找到另一种解决方案。我不知道如何以 std 方式解除阻塞在控制台上等待的线程,但该线程有 stackoverflow.com/questions/27710672/…
  • 谢谢!在 ExecuteOtherWork() 我与硬件通信 -> 所以如果设备挂起或崩溃我没有机会退出线程?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-17
  • 2021-08-13
  • 2013-09-03
  • 2015-05-04
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
相关资源
最近更新 更多