C++并發(fā)編程的實踐案例有很多,以下是一些常見的例子:
std::thread
和std::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::mutex
和std::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;
}
std::thread
、std::queue
、std::mutex
和std::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ù)和工具。