简单的任务池的实现
int run_thread5(int from, int to)
{
std::cout << __FUNCTION__ << ", currentTime E = " << std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count() << std::endl;
for(int i = from; i > to; --i)
{
std::cout << __FUNCTION__ << ", i = " << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << __FUNCTION__ << ", currentTime F = " << std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count() << std::endl;
return (from - to);
}
template<typename _Fn, typename... _Args>
class TaskPool
{
public:
TaskPool()
{
isRun = false;
}
~TaskPool()
{
isRun = false;
cond.notify_all();
for(int i = 0; i < threads.size(); ++i)
{
threads[i].join();
}
}
public:
int initTaskPool(const int threadCnt = 2)
{
isRun = true;
for(int i = 0; i < threadCnt; ++i)
{
threads.push_back(std::thread(&TaskPool<_Fn, _Args...>::run_thread, this));
}
return 0;
}
int addTask(_Fn&& fn, _Args&&... __args)
{
std::lock_guard<std::mutex> lg(mtx);
// std::function<_Fn> task = std::bind(std::forward<_Fn>(fn), std::forward<_Args>(__args)...); // OK
std::function<_Fn> task = std::bind(fn, __args...); // OK
// tasks.push_back(std::move(task));
tasks.push_back(task);
cond.notify_one();
return 0;
}
int count()
{
std::lock_guard<std::mutex> lg(mtx);
return tasks.size();
}
private:
void run_thread()
{
while(isRun)
{
std::function<_Fn> task;
{
std::unique_lock<std::mutex> lg(mtx);
cond.wait(lg, [&]{ return tasks.size() || isRun == false; });
if(isRun == false)
{
break;
}
task = std::move(*tasks.begin());
tasks.erase(tasks.begin());
}
// task(int(), int()); // OK
task(90, 80); // OK
}
}
public:
std::vector<std::thread> threads;
std::mutex mtx;
std::condition_variable cond;
std::atomic<bool> isRun;
std::vector<std::function<_Fn>> tasks;
};
int main()
{
{
TaskPool<int(int, int), int, int> taskPool;
int ret = taskPool.initTaskPool(1);
int count = 0;
while(count < 10)
{
int from = count;
int to = from - 10;
taskPool.addTask(run_thread5, std::move(from), std::move(to));
count++;
}
while(taskPool.count() != 0)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
// std::cout << "Main Thread !" << std::endl;
}
}
return 0;
}