C ++ 11懒惰工作线程初始化和空闲终止

时间:2014-10-01 22:57:48

标签: c++ multithreading c++11 thread-safety

目标是让一个懒惰的衍生工作线程在闲置一段时间后自行终止。我的目的是在一些网络代码中使用类似的技术,其中具有大量空闲线程被认为是不合需要的。下面是一个示例单例类,我希望能够完成这项工作。多线程不是我的强项,我很欣赏第二组眼睛,以确保我没有忽略一些明显的东西。

感谢你们的期待!

class lazyWorkerIdleTerminate {
    typedef enum state {
        STARTED,
        STOPPING,
        STOPPED
    } state_t;

    std::queue<std::string> queue;
    std::mutex              mutex;
    std::thread             thread;
    std::condition_variable condition;
    std::atomic<state_t>    state = ATOMIC_VAR_INIT(STOPPED);

    void process() {
        std::unique_lock<std::mutex> lock(mutex, std::defer_lock);

        while (true) {
            lock.lock();
            while (queue.empty()) {
                if (condition.wait_for(lock, std::chrono::seconds(30)) == std::cv_status::timeout || state == STOPPING) {
                    state = STOPPED;
                    return;
                }
            }
            std::string work = queue.front();
            queue.pop();
            lock.unlock();

            // Some processing here...
        }
    }

public:
    static lazyWorkerIdleTerminate& instance() {
        static lazyWorkerIdleTerminate instance;
        return instance;
    }

    void doWork(std::string work) {
        {
            std::lock_guard<std::mutex> lock(mutex);
            queue.push(work);
            if (state == STOPPED) {
                state = STARTED;
                if (thread.joinable()) thread.detach();
                thread = std::thread(&lazyWorkerIdleTerminate::process, this);
                return;
            }
        }
        condition.notify_one();
    }

    void stop() {
        {
            std::lock_guard<std::mutex> lock(mutex);
            if (state != STARTED) return;
            state = STOPPING;
        }
        condition.notify_one();
        thread.join();
    }

    lazyWorkerIdleTerminate() {}

    ~lazyWorkerIdleTerminate() {
        stop();
    }
};

0 个答案:

没有答案