循环计时器线程

3
我想要创建一个循环计时器线程池:每隔n秒,我们将运行任务。
在我的示例中,有两个任务。对于每个任务,我将创建一个线程来运行。我为每个任务添加了状态条件,如果状态是false,则不执行任何操作。我需要状态来控制计时器,可以调用计时器的开始/停止(抱歉,在这个代码中只有开始函数)。
以下是我的代码:
 #include <iostream>
#include <list>
#include <functional>
#include <map>
#include <thread>
#include <chrono>
#include <vector>
#include <mutex>

//using namespace std::chrono_literals;

void print_time()
{
    std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
    std::chrono::system_clock::duration tp = now.time_since_epoch();
    tp -= std::chrono::duration_cast<std::chrono::seconds>(tp);
    std::time_t ttp = std::chrono::system_clock::to_time_t(now);
    tm t = *gmtime(&ttp);

    std::printf("[%04u-%02u-%02u %02u:%02u:%02u.%03u]: ", t.tm_year + 1900,
                t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
                static_cast<unsigned>(tp/std::chrono::milliseconds(1)));
}

typedef std::function<void()> Callback;

enum E_NUM {
    NUM_ONE = 0,
    NUM_TWO
};

class Foo {
    public:
        static Foo& getInstance()
        {
            static Foo instance;
            return instance;
        }

        void init() {
            m_mapThreadStatus[NUM_ONE] = false;
            m_mapThreadStatus[NUM_TWO] = false;
            m_mapCallback[NUM_ONE] = std::bind(&Foo::test, this);
            m_mapCallback[NUM_TWO] = std::bind(&Foo::foo_test, this);
        }

        void addTimer(E_NUM id, int num_seconds) {
            std::thread th ([id, num_seconds] () {
                    std::cout << std::this_thread::get_id() << " id: " << id << "\tseconds: " << num_seconds << std::endl;
                    while (1)
                    {
                        if ( Foo::getInstance().getStatus(id) == true)
                        {
                            Foo::getInstance().callfunctor(id);
                            std::this_thread::sleep_for(std::chrono::seconds(num_seconds));
                        }
                        else
                        {
                        }
                        //std::this_thread::sleep_for(std::chrono::seconds(num_seconds));
                    }
                });
            m_mapThreads[id] = std::move(th);
        }

        void callfunctor(E_NUM id) {
            m_mapCallback[id]();
        }

        void startTimers(E_NUM id) {    
            m_mapThreadStatus[id] = true;
            if (m_mapThreads[id].joinable())
            {
                m_mapThreads[id].join();
            }
        }

        bool getStatus(E_NUM id) { 
            return m_mapThreadStatus[id];}

    private:
        void test() {
            print_time();
            std::cout << std::this_thread::get_id() << std::endl;
            std::cout << "\033[1;31m" << __PRETTY_FUNCTION__ << "\033[0m" << std::endl;
        }
        void foo_test() {
            print_time();
            std::cout << std::this_thread::get_id() << std::endl;
            std::cout << "\033[1;32m" << __PRETTY_FUNCTION__ << "\033[0m" << std::endl;
        }
        Foo() {init();}
        std::map<E_NUM, Callback> m_mapCallback;
        std::vector<std::thread> m_threads;
        std::map<E_NUM, std::thread> m_mapThreads;
        std::map<E_NUM, bool> m_mapThreadStatus;
};

int main()
{
    Foo::getInstance().addTimer(NUM_ONE, 1);
    Foo::getInstance().addTimer(NUM_TWO, 2);
    Foo::getInstance().startTimers(NUM_ONE);
    Foo::getInstance().startTimers(NUM_TWO);
    return 0;
}

但我的问题是: 1. 看起来只有一个任务在运行,而不是期望的两个。
40557398533888 id: 0    seconds: 1140557390141184 id: 1 seconds: 2
[2019-05-28 11:56:49.770]: 140557398533888
void Foo::test()

[2019-05-28 11:56:50.770]: 140557398533888
void Foo::test()
[2019-05-28 11:56:51.771]: 140557398533888
void Foo::test()
[2019-05-28 11:56:52.771]: 140557398533888
void Foo::test()
[2019-05-28 11:56:53.772]: 140557398533888
void Foo::test()
  1. 经典问题:当我们创建std::thread时,它是立即运行的,对吗?例如:链接。那么,我该如何改进我的代码以在添加定时器后启动?

编辑 1:

我在Foo中添加了函数:

class Foo {
    ...
    void startTimers() {
        m_mapThreads[NUM_ONE].join();
        m_mapThreads[NUM_TWO].join();
    }
};

我在main函数结尾调用了这个函数,它完美地运行了。谢谢。

1个回答

3
考虑您的Foo::startTimers实现...
void startTimers (E_NUM id)
{    
    m_mapThreadStatus[id] = true;
    if (m_mapThreads[id].joinable()) {
        m_mapThreads[id].join();
    }
}

你使用id标识线程,并使用start启动线程...
m_mapThreadStatus[id] = true;

但你需要加入那个线程。结果是,当你启动一个给定的线程时,你的代码将阻塞,直到该线程完成。因此,使用...

int main()
{
    Foo::getInstance().addTimer(NUM_ONE, 1);
    Foo::getInstance().addTimer(NUM_TWO, 2);
    Foo::getInstance().startTimers(NUM_ONE);
    Foo::getInstance().startTimers(NUM_TWO);
    return 0;
}

The line...

Foo::getInstance().startTimers(NUM_ONE);

将会阻塞,直到与NUM_ONE相关联的线程结束 -- 在当前情况下永远不会结束 -- 并且Foo::getInstance().startTimers(NUM_TWO)永远不会被调用。


谢谢您指出我的错误。我忘记了主线程会等待加入的线程完成。 - GAVD

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接