C++11 STL线程库实现一个简单的线程池

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

使用C++11 STL线程库实现一个线程池。处理机制是抢占式的,即所有线程从一个队列(std::queue)中获取任务执行(计算字符串简单HASH值),使用std::mutex和std::conditional_variable实现队列访问并发协调。



#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

static std::mutex G_lockPrint;

void print_message(int value, const string& str) {
    lock_guard lock(G_lockPrint);
    cout< strqueue;

    volatile bool stop = false;

    for(int i = 0; i < THREAD_COUNT; ++i ) {
        thpool[i] = thread([&quelock, &quecv, &strqueue, &stop]()
            {
                string str;
                while ( !stop ) {
                    {
                        unique_lock lock(quelock);
                        if ( strqueue.empty() ) {
                            auto ret = quecv.wait_for(lock, chrono::seconds(1));
                            if ( ret == cv_status::timeout) continue;
                        }

                        if ( !strqueue.empty() ) {
                            str = strqueue.front();
                            strqueue.pop();
                        } else {
                            continue;
                        }
                    }

                    int hash = 0;
                    for(size_t i = 0; i < str.length(); ++i) {
                        hash = (hash << 5) - i + str[i];
                    }
                    print_message(hash, str);
                } // end while
            }
        );
    }

    for(int i = 0; i < 100000; ++i) {
        stringstream ss;
        ss<<"aaaaa_"< lock(quelock);
        strqueue.push(ss.str());
        quecv.notify_one();
    }

    while (1) {
        this_thread::sleep_for(chrono::seconds(1));
        lock_guard lock(quelock);
        if ( strqueue.empty()) break;
    }
    stop = true;
    for(int i = 0; i < THREAD_COUNT; ++i ) thpool[i].join();
    cout<<"program exit"<

 

 

 

 

转载于:https://my.oschina.net/luckysym/blog/1841768

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