溫馨提示×

C++并發(fā)編程有哪些實踐案例

c++
小樊
81
2024-11-09 06:52:41
欄目: 編程語言

C++并發(fā)編程的實踐案例有很多,以下是一些常見的例子:

  1. 多線程計數(shù)器:這是一個簡單的多線程計數(shù)器示例,使用C++11的std::threadstd::atomic實現(xiàn)。
#include <iostream>
#include <thread>
#include <atomic>
#include <vector>

std::atomic<int> counter(0);

void increment() {
    for (int i = 0; i < 1000; ++i) {
        ++counter;
    }
}

int main() {
    std::vector<std::thread> threads;
    for (int i = 0; i < 10; ++i) {
        threads.emplace_back(increment);
    }

    for (auto& t : threads) {
        t.join();
    }

    std::cout << "Counter: " << counter << std::endl;
    return 0;
}

2.生產(chǎn)者消費(fèi)者模型:這是一個使用std::queue、std::mutexstd::condition_variable實現(xiàn)的生產(chǎn)者消費(fèi)者模型示例。

#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>

std::queue<int> dataQueue;
std::mutex mtx;
std::condition_variable cv;

void producer() {
    for (int i = 0; i < 10; ++i) {
        std::unique_lock<std::mutex> lock(mtx);
        dataQueue.push(i);
        cv.notify_one();
    }
}

void consumer() {
    while (true) {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, [] { return !dataQueue.empty(); });
        int value = dataQueue.front();
        dataQueue.pop();
        std::cout << "Consumed: " << value << std::endl;
    }
}

int main() {
    std::thread producerThread(producer);
    std::thread consumerThread(consumer);

    producerThread.join();
    consumerThread.join();

    return 0;
}
  1. 線程池:這是一個使用std::thread、std::queuestd::mutexstd::condition_variable實現(xiàn)的簡單線程池示例。
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <functional>

class ThreadPool {
public:
    ThreadPool(size_t numThreads) : stop(false) {
        for (size_t i = 0; i < numThreads; ++i) {
            workers.emplace_back([this] {
                while (true) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(this->mtx);
                        this->cond.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
                        if (this->stop && this->tasks.empty()) {
                            return;
                        }
                        task = std::move(this->tasks.front());
                        this->tasks.pop();
                    }
                    task();
                }
            });
        }
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(mtx);
            stop = true;
        }
        cond.notify_all();
        for (auto& worker : workers) {
            worker.join();
        }
    }

    template <typename F, typename... Args>
    void enqueue(F&& f, Args&&... args) {
        {
            std::unique_lock<std::mutex> lock(mtx);
            tasks.emplace([f, args...] { f(args...); });
        }
        cond.notify_one();
    }

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;
    std::mutex mtx;
    std::condition_variable cond;
    bool stop;
};

void task(int id) {
    std::cout << "Task " << id << " is running on thread " << std::this_thread::get_id() << std::endl;
}

int main() {
    ThreadPool pool(4);
    for (int i = 0; i < 10; ++i) {
        pool.enqueue(task, i);
    }

    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 0;
}

這些示例展示了C++并發(fā)編程的一些基本概念和實踐方法。在實際項目中,你可能需要根據(jù)具體需求選擇合適的并發(fā)編程技術(shù)和工具。

0