C++ 手搓线程池(改进)
本文最后更新于6 天前,其中的信息可能已经过时,如有错误请留言

具体代码如下:

#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 $@

感谢阅读!如有疑问请留言
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇