才知道一个新知识,还能这样提高效率: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) {
}
};