C++11中多线程例子

C++11开始自带线程相关的操作库。这里举个例子,以并发编程最经典的例子,生产者消费者的例子来示例在C++11使用标准库提供的线程库来进行并发编程。

这里为了方便线程的使用,参考了android源码中对pthread的封装。

class Thread
{
public:
    Thread()
        : m_running(false)
    {
    }

    virtual ~Thread()
    {
        if(m_running) {
            m_running = false;
        }
    }

    Thread(const Thread&) = delete;

    Thread& operator=(const Thread&) = delete;

    virtual bool threadRun() = 0;

    bool start()
    {
        if (m_running) {

        }
        else {
            m_running = true;
            m_thread.reset(new std::thread(std::bind(&Thread::runImpl, this)));
            m_thread->detach();
        }
        return m_running;
    }

    bool stop()
    {
        return m_running = false;
    }


private:
    void runImpl()
    {
        while (m_running && threadRun());
    }

    std::shared_ptr<std::thread> m_thread;
    std::atomic_bool m_running;

};

对其进行了简单的封装,如果需要使用线程,继承Thread和实现threadRun这个接口,如果其返回true,那么线程将重复调用这个接口,如果其返回为false,那么线程将退出执行。

生产者

class ProduceThread : public Thread
{
public:
    ProduceThread(std::queue<int> &q_, std::condition_variable& cv_, std::mutex& mutex_)
        : Thread()
        , m_q(q_)
        , m_cv(cv_)
        , m_mutex(mutex_)
    {

    }

    bool threadRun()
    {
        sleep(rand() % 9);
        std::unique_lock<std::mutex> _lock(m_mutex);
        int _t = rand();
        m_q.push(_t);
        std::cout << "ProduceThread---" << _t << '\n';
        m_cv.notify_one();
        return true;
    }

private:
    std::queue<int>& m_q;
    std::condition_variable& m_cv;
    std::mutex& m_mutex;
};

消费者

class ConsumerThread : public Thread
{
public:
    ConsumerThread(std::queue<int> &q_, std::condition_variable& cv_, std::mutex& mutex_)
        : Thread()
        , m_q(q_)
        , m_cv(cv_)
        , m_mutex(mutex_)
    {

    }

    bool threadRun()
    {
    sleep(rand() % 4)
        std::unique_lock<std::mutex> _lock(m_mutex);
        if (m_q.empty()) {
            m_cv.wait(_lock);
        } else {
            std::cout << "ConsumerThread---" << m_q.front() << '\n';
            m_q.pop();
        }
        return true;

    }

private:
    std::queue<int>& m_q;
    std::condition_variable& m_cv;
    std::mutex& m_mutex;
};

这里使用了condition_variable来进行线程间的同步。

int main(int argc, char *argv[])
{
    std::cout << "Hello World!" << std::endl;

    std::condition_variable _cv;
    std::mutex _mutex;
    std::queue<int> _queue;

    ProduceThread pt(_queue, _cv, _mutex);
    ConsumerThread cp(_queue, _cv, _mutex);

    cp.start();
    pt.start();
    sleep(20);

    return 0;
}

你可能感兴趣的:(C/C++,c++)