本文最后更新于7 天前,其中的信息可能已经过时,如有错误请留言
具体代码如下:
#include <iostream>
#include <functional>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <thread>
#include <atomic>
using namespace std;
class ThreadPool {
private:
queue<function<void()>> taskQueue;
mutex mtx;
condition_variable cond;
vector<thread> threads;
atomic<bool> stop;
public:
ThreadPool(size_t threadNum):stop(false) {
for (size_t i = 0; i < threadNum; i++) {
threads.emplace_back([this]() {
cout << this_thread::get_id() << "th thread start running..." << endl;
while (true) {
function<void()> task;
{
unique_lock<mutex> lock(mtx);
cond.wait(lock, [this]() {
return stop.load() || !taskQueue.empty();
});
if (stop.load() && taskQueue.empty()) {
return;
}
task = move(taskQueue.front());
taskQueue.pop();
}
task();
}
});
}
}
~ThreadPool() {
Stop();
}
void Stop() {
if (stop.exchange(true)) {
return;
}
cond.notify_all();
for (thread& th : threads) {
if (th.joinable()) th.join();
}
}
void AddTask(function<void()>&& task) {
{
lock_guard<mutex> lock(mtx);
taskQueue.emplace(move(task));
}
cond.notify_one();
}
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
};
int main() {
ThreadPool pool(3);
pool.AddTask([](){
cout << this_thread::get_id() << "th thread executing task1..." << endl;
this_thread::sleep_for(chrono::seconds(2));
cout << "task1 end..." << endl;
});
pool.AddTask([](){
cout << this_thread::get_id() << "th thread executing task2..." << endl;
this_thread::sleep_for(chrono::seconds(2));
cout << "task2 end..." << endl;
});
pool.AddTask([](){
cout << this_thread::get_id() << "th thread executing task3..." << endl;
this_thread::sleep_for(chrono::seconds(2));
cout << "task3 end..." << endl;
});
return 0;
}
编译脚本如下:
# Makefile
# 编译器
CXX := g++
# 编译选项
CXXFLAGS := -std=c++11 -pthread
# 目标文件名
TARGET := main
# 源文件(可以在这里添加多个 .cpp 文件)
SRC := code.cpp
# 自动生成对应的 .o 文件列表
# OBJ := $(SRC:.cpp=.o)
# 最终目标
$(TARGET): $(SRC)
$(CXX) $(CXXFLAGS) -o $(TARGET) $(SRC)
# 通用规则:把每个 .cpp 编译成 .o
# %.o: %.cpp
# $(CXX) $(CXXFLAGS) -c $< -o $@


