#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <thread>
#include <queue>
#include <functional>
#include <mutex>
using namespace std;
class ThreadPool
{
public:
ThreadPool(int numThreads) :m_Stop(false)
{
for (int i = 0; i != numThreads; ++i)
{
m_Threads.emplace_back([this]
{
while (true)
{
std::unique_lock<std::mutex> lock(m_Mutex);
m_Condition.wait(lock, [this] { return !m_Tasks.empty() || m_Stop; });
if (m_Stop && m_Tasks.empty()) return;
std::function<void()> task(std::move(m_Tasks.front()));
m_Tasks.pop();
lock.unlock();
task();
}
});
}
}
~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(m_Mutex);
m_Stop = true;
}
m_Condition.notify_all();
for (auto &t : m_Threads)
{
t.join();
}
}
ThreadPool(ThreadPool &) = delete;
ThreadPool &operator=(const ThreadPool &) = delete;
template<class F, class... Args>
void enQueue(F &&f, Args&&... args)
{
std::function<void()> task =
std::bind(std::forward<F>(f), std::forward<Args>(args)...);
{
std::unique_lock<std::mutex> lock(m_Mutex);
m_Tasks.emplace(std::move(task));
}
m_Condition.notify_all();
}
private:
std::vector<std::thread> m_Threads;
std::queue<std::function<void()>> m_Tasks;
std::mutex m_Mutex;
std::condition_variable m_Condition;
bool m_Stop;
};
int main()
{
ThreadPool th_pool(4);
for (int i = 0; i != 10; ++i)
{
th_pool.enQueue([i]
{
std::cout << "task : " << i << " is running " << '\n';
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "task : " << i << " is done " << '\n';
});
}
system("pause");
return EXIT_SUCCESS;
}
输出:
task : 0 is running
task : 1 is running
task : 2 is running
task : 3 is running
请按任意键继续. . . task : 0 is done
task : 4 is running
task : 2 is done
task : 5 is running
task : 1 is done
task : 6 is running
task : 3 is done
task : 7 is running
task : 4 is done
task : task : 85 is done
is running
task : 6task : 9 is running is done
task : 7 is done
task : 8 is done
task : 9 is done
参考:https://www.bilibili.com/video/BV1d841117SH?p=9&vd_source=d63f54e500587f56976cc02586e53496
标签:std,task,lock,C++,running,done,线程,include From: https://www.cnblogs.com/huvjie/p/18425257