检查线程是否处于活动状态

时间:2021-02-18 22:59:43

标签: c++ multithreading

需要在以下包装器中添加线程检查:

class threadWrapper{
    private:
        std::thread m_thread;

    void set_sched_priority(const int sched, const int priority){
        sched_param sparam;
        sparam.sched_priority = priority;
        pthread_setschedparam(m_thread.native_handle(), sched, &sparam);
    }
    public:
    bool isActive(){
        //Dont know how to achieve this
    }

    template< class...Args > 
    explicit threadWrapper(const int sched, const int priority, Args&&... args):
    m_thread(std::forward<Args>(args)...)
    {
        set_sched_priority(sched, priority);
    };

    threadWrapper &operator=(threadWrapper&&) = default;
    threadWrapper &operator=(const threadWrapper&) = delete;
    threadWrapper(threadWrapper&) = delete;
    
    //Need to work on this:
    ~threadWrapper(){
        if(m_thread.joinable()) m_thread.join();
    }
};

我想实现一个函数来检查线程健康状况 isActive() 并暂停线程执行 suspend()

  1. 尝试使用 thread::joinable() 方法,但对于 isActive() 总是返回 true。

  2. 添加 future 和 promise 对象作为私有成员变量:

//Constructor change 
explicit threadWrapper(const int sched, const int priority, Args&&... args):
   future(p.get_future()),.......
   
bool isActive(){
   return !(this->future.wait_for(0ms) == std::future_status::ready);
}

这不起作用,因为函数 isActive 总是返回 true。 我不确定如何进行函数实现,我搜索的其他资源都没有帮助

1 个答案:

答案 0 :(得分:0)

只需编写您需要的代码。显而易见的方法是使用两个受互斥锁保护的布尔标志,一个指示线程是否处于活动状态,一个指示线程是否应该挂起。

当线程变为非活动状态时,它应该获取互斥锁并将活动标志设置为 false。

当线程处于可以安全挂起的点时,它应该获取互斥锁并检查挂起标志。

要挂起线程,获取互斥锁,检查活动标志,并设置挂起标志。

如果您需要线程能够等待直到它被取消挂起,请为此使用条件变量。如果您需要外部线程能够等到线程挂起,请使用另一个条件变量和线程在挂起时设置为 true 的标志。

您实际上只是根据需要编写所需的每个功能。这些是最简单的方法,但效果很好。