c++ Package std::thread并实现is_running()方法

vsnjm48y  于 2023-07-01  发布在  其他
关注(0)|答案(1)|浏览(107)

我一直在用C17替换现有的框架,必须保留现有的逻辑,但用标准C替换框架。
我需要一个is_running()方法用于std::thread。我的第一个想法是在 Package 器类的thread函数中使用std::atomic和compare_exchange_strong(),该函数调用传入的thread函数。这样我至少知道传入的函数何时返回。

  • 一个要求是,即使是bug,我也不能更改逻辑,因此,其他C++线程方法将不可接受。
h7appiyu

h7appiyu1#

既然你需要向后兼容,你可以这样做。

#include <chrono>
#include <iostream>
#include <thread>
#include <memory>

using namespace std::chrono_literals;

// make a wrapper around thread
// that can r
class my_thread_t
{
public:
    ~my_thread_t()
    {
        m_thread->join();
    }

    template<typename fn_t>
    void start(fn_t&& fn)
    {
        // Wrap the function in a lambda expression
        // of our own which will keep track of the 
        // state of the thread (or at least of the
        // function call on that thread)
        auto wrapped_fn = [&]
        {
            m_state = state_v::running;
            fn();
            m_state = state_v::stopped;
        };

        m_thread = std::make_unique<std::thread>(wrapped_fn);
    }

    bool is_running() const noexcept
    {
        return (m_state == state_v::running);
    }

private:
    enum class state_v
    {
        initial,
        running,
        stopped
    };

    std::atomic<state_v> m_state{ state_v::initial };
    std::unique_ptr<std::thread> m_thread;
    
};

void show_status(const my_thread_t& thread)
{
    if (thread.is_running())
    {
        std::cout << "thread is running\n";
    }
    else
    {
        std::cout << "thread is not running\n";
    }
}

int main()
{
    my_thread_t thread;

    show_status(thread);

    thread.start([] { std::this_thread::sleep_for(1s); });

    for (std::size_t n{0ul}; n < 6; ++n)
    {
        show_status(thread);
        std::this_thread::sleep_for(250ms);
    }
    
    return 0;
}

相关问题