直接上代码:
#include <mutex>
#include <condition_variable>
#include <functional>
#include <queue>
#include <thread>
class fixed_thread_pool {
public:
explicit fixed_thread_pool(size_t thread_count) //显示的声明构造函数
: data_(std::make_shared<data>()) {
for (size_t i = 0; i < thread_count; ++i) {
std::thread([data = data_] {
std::unique_lock<std::mutex> lk(data->mtx_);
for (;;) {
if (!data->tasks_.empty()) {
auto current = std::move(data->tasks_.front());
data->tasks_.pop();
lk.unlock();
current();
lk.lock();
}
else if (data->is_shutdown_) {
break;
}
else {
data->cond_.wait(lk);
}
}
}).detach();
}
}
fixed_thread_pool() = default;
fixed_thread_pool(fixed_thread_pool&&) = default;
~fixed_thread_pool() {
if ((bool)data_) {
{
std::lock_guard<std::mutex> lk(data_->mtx_);
data_->is_shutdown_ = true;
}
data_->cond_.notify_all();
}
}
//template <class F>
//void execute(F&& task) {
// {
// std::lock_guard<std::mutex> lk(data_->mtx_);
// data_->tasks_.emplace(std::forward<F>(task));
// }
// data_->cond_.notify_one();
//}
//可选参数
template <class F, class... Args>
void execute2(F&& func, Args&&... args) {
{
auto task = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
std::lock_guard<std::mutex> lk(data_->mtx_);
data_->tasks_.emplace(std::forward<decltype(task)>(task));
}
data_->cond_.notify_one();
}
private:
struct data {
std::mutex mtx_;
std::condition_variable cond_;
bool is_shutdown_ = false;
std::queue<std::function<void()>> tasks_;
};
std::shared_ptr<data> data_;
};
测试代码:
#include<iostream>
#include<ctime>
#include<cstdlib>
#include<string>
void fun()
{
std::cout << "Work in thread: " << std::this_thread::get_id() << std::endl;
std::cout << "i am fun" << std::endl;
}
void fun1(int i)
{
std::cout << "Work in thread: " << std::this_thread::get_id() << std::endl;
std::cout << "i =" << i << std::endl;
}
int main()
{
std::shared_ptr<fixed_thread_pool>thread_pool;
thread_pool = std::make_shared<fixed_thread_pool>(500);
for (int i = 0; i < 1000; i++)
{
thread_pool->execute2(fun);
fun();
}
for (int i = 0; i < 1000; i++)
{
thread_pool->execute2(fun1, 1);
//fun1(i);
}
getchar();
}