阅读量:2
C++并发编程的实践案例有很多,以下是一些常见的例子:
- 多线程计数器:这是一个简单的多线程计数器示例,使用C++11的
std::thread和std::atomic实现。
#include
#include
#include
#include
std::atomic<int> counter(0);
void increment() {
for (int i = 0; i < 1000; ++i) {
++counter;
}
}
int main() {
std::vector 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.生产者消费者模型:这是一个使用std::queue、std::mutex和std::condition_variable实现的生产者消费者模型示例。
#include
#include
#include
#include
#include
std::queue<int> dataQueue;
std::mutex mtx;
std::condition_variable cv;
void producer() {
for (int i = 0; i < 10; ++i) {
std::unique_lock lock(mtx) ;
dataQueue.push(i);
cv.notify_one();
}
}
void consumer() {
while (true) {
std::unique_lock 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实现的简单线程池示例。
#include
#include
#include
#include
#include
#include
#include
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 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 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 lock(mtx) ;
tasks.emplace([f, args...] { f(args...); });
}
cond.notify_one();
}
private:
std::vector workers;
std::queuevoid()>> 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++并发编程的一些基本概念和实践方法。在实际项目中,你可能需要根据具体需求选择合适的并发编程技术和工具。
以上就是关于“C++并发编程有哪些实践案例”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm