如何实现GetCurrentThread(线程局部储存)

参考:http://www.cnblogs.com/lzjsky/archive/2010/09/01/1814843.html

可以看到linux和windows上的两种实现方法。pthread有windows兼容库:https://sourceware.org/pthreads-win32/

C++11也提供了thread_local 关键字,如:thread_local void *a; 这个变量里存的数据就是线程局部变量,不同线程读出的内容不同~

vs2015测试项目下载:testthreadloca.7z

C++11线程安全的队列

才知道一个新知识,还能这样提高效率:http://www.oschina.net/translate/a-fast-lock-free-queue-for-cpp?cmp(快速无锁队列)

typedef const std::function<void(void)> MyFun;
class XThreadPool {
private:
    int mThreadNum = 0;
    std::queue<MyFun> queue;
    std::mutex mutex;
    std::condition_variable cv;
    void runLoop() {
        do {
            std::unique_lock<std::mutex> lk(mutex);
            if(queue.size() > 0) {
                queue.back()();
                queue.pop();
            } else {
                cv.wait(lk);
            }
        } while (1);
    }
public:
    void startNewThread() {
        std::thread thread(std::bind(&XThreadPool::runLoop, this));
        thread.detach();
        ++mThreadNum;
    }
    XThreadPool() {
        startNewThread();
    }
    XThreadPool(int threadNum) {
        for (int i = 0; i < threadNum; ++i) {
            startNewThread();
        }
    }
    int getThreadNum() {
        return mThreadNum;
    }
    virtual ~XThreadPool() {
    }
    void dispatchAsync(MyFun &fun) {
        
        mutex.lock();
        queue.push(fun);
        mutex.unlock();
        cv.notify_one();
    }
    void dispatchAfter(MyFun &fun, long delayMS) {
        
    }
};