溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在Linux C++中實現多線程的公平調度

發布時間:2024-11-18 10:01:15 來源:億速云 閱讀:155 作者:小樊 欄目:編程語言

在 Linux 中,C++11 標準提供了對多線程編程的支持

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <vector>
#include <chrono>
#include <functional>

class FairScheduler {
public:
    void add_task(std::function<void()> task) {
        std::unique_lock<std::mutex> lock(queue_mutex_);
        tasks_.push(task);
        lock.unlock();
        condition_.notify_one();
    }

    void run() {
        while (true) {
            std::function<void()> task;
            {
                std::unique_lock<std::mutex> lock(queue_mutex_);
                condition_.wait(lock, [this] { return !tasks_.empty(); });
                task = std::move(tasks_.front());
                tasks_.pop();
            }
            task();
        }
    }

private:
    std::queue<std::function<void()>> tasks_;
    std::mutex queue_mutex_;
    std::condition_variable condition_;
};

int main() {
    FairScheduler scheduler;

    // 創建線程
    std::vector<std::thread> threads;
    for (int i = 0; i < 5; ++i) {
        threads.emplace_back([&scheduler] { scheduler.run(); });
    }

    // 添加任務
    for (int i = 0; i < 10; ++i) {
        int task_id = i;
        scheduler.add_task([task_id] {
            std::cout << "Task " << task_id << " is running on thread " << std::this_thread::get_id() << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        });
    }

    // 等待線程結束
    for (auto& thread : threads) {
        thread.join();
    }

    return 0;
}

在這個示例中,我們創建了一個名為 FairScheduler 的類,它使用一個隊列來存儲待執行的任務。add_task 方法用于向隊列中添加任務,而 run 方法用于執行隊列中的任務。run 方法使用條件變量來等待新任務的到來,從而實現公平調度。

main 函數中,我們創建了一個 FairScheduler 實例,并啟動了 5 個線程來執行任務。然后,我們向隊列中添加了 10 個任務,每個任務都會輸出其 ID 和運行它的線程 ID。最后,我們等待所有線程結束。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

c++
AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女