引言 void threadFunction() { int main() { t1.join(); return 0; std::mutex mtx; void threadFunction() { class ThreadPool { template auto task = std::make_shared< std::packaged_task std::future if (stop) tasks.emplace([task]() { (*task)(); }); ~ThreadPool() { private: std::mutex queue_mutex; bool stop = false; std::shared_mutex rw_mutex; void read() { void write() { auto future = std::async(std::launch::async, []() { std::cout << future.get() << std::endl;
3.2 std::jthread
C++20引入了
std::jthread
,它是
std::thread
的替代品,提供了更好的线程管理和错误处理。
#include jthread t1([]() {
在当今的多核处理器时代,并发编程已成为软件开发的重要组成部分。C++作为一种高效的编程语言,提供了丰富的并发编程工具和库。本文将带你从C++并发编程的基础知识开始,逐步深入到高级技巧,帮助你掌握多线程高效编程。
一、C++并发编程基础
1.1 多线程概念
多线程是指在同一程序中同时执行多个线程。每个线程可以独立地执行程序的一部分,从而提高程序的执行效率。
1.2 C++11标准中的线程库
C++11标准引入了
#include
// 线程执行的代码
}
std::thread t1(threadFunction);
std::thread t2(threadFunction);
t2.join();
}
1.3 线程同步
在多线程环境中,线程之间可能会存在竞争条件和死锁等问题。为了解决这个问题,C++提供了互斥锁(mutex)、条件变量(condition_variable)和原子操作(atomic)等同步机制。
#include
std::lock_guard
// 临界区代码
}
二、C++11并发编程进阶
2.1 线程池
线程池可以有效地管理线程资源,避免频繁创建和销毁线程的开销。
#include
#include
#include
#include
public:
ThreadPool(size_t threads) {
for (size_t i = 0; i < threads; ++i) {
workers.emplace_back([this] {
for (;;) {
std::function
{
std::unique_lock
this->condition.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();
}
});
}
}
auto enqueue(F&& f, Args&&… args)
-> std::future
using return_type = typename std::result_of
std::bind(std::forward
);
{
std::unique_lock
throw std::runtime_error(“enqueue on stopped ThreadPool”);
}
condition.notify_one();
return res;
}
{
std::unique_lock
stop = true;
}
condition.notify_all();
for (std::thread &worker: workers)
worker.join();
}
std::vector
std::queue< std::function
std::condition_variable condition;
};
2.2 读写锁
读写锁允许多个线程同时读取数据,但只有一个线程可以写入数据。
#include
std::shared_lock
// 读取数据
}
std::unique_lock
// 写入数据
}
三、C++14及以后版本的并发编程
3.1 async和await
C++17引入了
std::async
和
std::await
,使得异步编程更加简单。
#include
// 异步执行的代码
});
// 线程执行的代码
});
四、总结
C++并发编程是一项重要的技能,掌握并发编程可以让你编写出更加高效、可靠的程序。本文从C++并发编程的基础知识开始,逐步深入到高级技巧,希望能帮助你更好地掌握多线程高效编程。