溫馨提示×

如何在C++線程類中實現(xiàn)任務(wù)分配

c++
小樊
83
2024-08-29 22:47:42
欄目: 編程語言

在 C++ 中,可以使用` 庫來創(chuàng)建線程并分配任務(wù)

#include<iostream>
#include<vector>
#include<thread>
#include <mutex>

class Task {
public:
    virtual void execute() = 0;
};

class PrintTask : public Task {
public:
    PrintTask(const std::string& message) : message_(message) {}

    void execute() override {
        std::cout << "Thread "<< std::this_thread::get_id() << ": "<< message_<< std::endl;
    }

private:
    std::string message_;
};

class ThreadPool {
public:
    ThreadPool(size_t num_threads) {
        for (size_t i = 0; i < num_threads; ++i) {
            threads_.emplace_back(&ThreadPool::worker, this);
        }
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(queue_mutex_);
            stop_ = true;
        }
        condition_.notify_all();
        for (auto& thread : threads_) {
            thread.join();
        }
    }

    void add_task(Task* task) {
        std::unique_lock<std::mutex> lock(queue_mutex_);
        tasks_.push(task);
        condition_.notify_one();
    }

private:
    void worker() {
        while (true) {
            Task* task = nullptr;
            {
                std::unique_lock<std::mutex> lock(queue_mutex_);
                condition_.wait(lock, [this] { return !tasks_.empty() || stop_; });
                if (stop_) {
                    break;
                }
                task = tasks_.front();
                tasks_.pop();
            }
            task->execute();
        }
    }

    std::vector<std::thread> threads_;
    std::queue<Task*> tasks_;
    std::mutex queue_mutex_;
    std::condition_variable condition_;
    bool stop_ = false;
};

int main() {
    ThreadPool pool(4); // 創(chuàng)建一個包含 4 個線程的線程池

    // 添加任務(wù)到線程池
    for (int i = 0; i < 10; ++i) {
        pool.add_task(new PrintTask("Hello from task " + std::to_string(i)));
    }

    // 等待所有任務(wù)完成
    // 注意:這里沒有刪除任務(wù)對象,實際應(yīng)用中需要考慮內(nèi)存管理
    std::this_thread::sleep_for(std::chrono::seconds(2));

    return 0;
}

這個示例中,我們定義了一個 Task 基類和一個派生自 TaskPrintTask 類。ThreadPool 類負(fù)責(zé)管理線程和任務(wù)隊列。add_task 方法用于向線程池添加新任務(wù)。線程池中的每個線程都會從任務(wù)隊列中獲取任務(wù)并執(zhí)行它。

請注意,這個示例沒有處理任務(wù)對象的內(nèi)存管理。在實際應(yīng)用中,你需要考慮如何安全地刪除任務(wù)對象以避免內(nèi)存泄漏。可以考慮使用智能指針(如 std::shared_ptrstd::unique_ptr)來管理任務(wù)對象的生命周期。

0