知识体系
thread
C++ thread中最常用的两个函数是join和detach,怎么选择呢,简单来说,假如盼望等候线程结束,用join,假如盼望异步执行,且不等候执行结果,那么就用detach;thread_local可以简单理解为一个线程级别的全局变量;线程id在调试多线程程序时黑白常有用的东西;
C++11本身没有提供线程池;可以参考第三方的实现:https://github.com/progschj/ThreadPool
- #ifndef THREAD_POOL_H
- #define THREAD_POOL_H
- #include <vector>
- #include <queue>
- #include <memory>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- #include <future>
- #include <functional>
- #include <stdexcept>
- class ThreadPool {
-
- public:
- ThreadPool(size_t);
- template<class F, class... Args>
- auto enqueue(F&& f, Args&&... args)
- -> std::future<typename std::result_of<F(Args...)>::type>;
- ~ThreadPool();
- private:
- // need to keep track of threads so we can join them
- std::vector< std::thread > workers;
- // the task queue
- std::queue< std::function<void()> > tasks;
-
- // synchronization
- std::mutex queue_mutex;
- std::condition_variable condition;
- bool stop;
- };
-
- // the constructor just launches some amount of workers
- inline ThreadPool::ThreadPool(size_t threads)
- : stop(false)
- {
-
- for(size_t i = 0;i<threads;++i)
- workers.emplace_back(
- [this]
- {
-
- for(;;)
- {
-
- std::function<void
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |