线程共享进程的内存地址,因此可以并发访问进程中的变量、堆和引用等。
线程有自己的栈。
C++ thread库
多线程管理
// 创建线程
std::thread t(fun,arg1,arg2);
// 等待线程
t.join();
//分离线程
t.detach();
//获取CPU核数
unsigned concurrent_count = thread::hardware_concurrency();
//获取线程id
std::thread::id this_id = std::this_thread::get_id();
mutex互斥锁
mutex是最基本的锁,使用时要分别lock和unlock。
mutex是被操作的基本单元,其余API都是管理mutex的。
// 基础锁
#include <iostream>
#include <mutex>
#include <thread>
std::mutex mtx; // 创建一个互斥量
void print(int n) {
mtx.lock(); // 加锁
std::cout << "Thread " << n << std::endl;
mtx.unlock(); // 解锁
}
int main() {
std::thread threads[5];
for (int i = 0; i < 5; i++) {
threads[i] = std::thread(print, i);
}
for (int i = 0; i < 5; i++) {
threads[i].join();
}
return 0;
}
单锁管理
lock_guard是一个RAII类型管理锁的类,其特点是构造时调用lock,析构时调用unlock。
// RAII型锁
#include <mutex>
std::mutex m;
void foo()
{
std::lock_guard<std::mutex> lock(m);
//临界区
}
std::unique_lock 支持lock(), try_lock()和unlock()成员函数,所以被这些函数调用并加锁,可以被unlock提前解锁,也可以离开作用域后自动解锁。
死锁管理
死锁的发生是因为锁嵌套导致的,避免死锁的方式有:
- 规定嵌套锁的访问顺序,
- 减小锁的颗粒度,
- 其次C++还提供了多个类来管理嵌套锁。
lock
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mutex1, mutex2;
void worker1()
{
std::lock(mutex1, mutex2);
std::lock_guard<std::mutex> lock1(mutex1, std::adopt_lock);
std::lock_guard<std::mutex> lock2(mutex2, std::adopt_lock);
// 对共享资源进行访问
std::cout << "Worker 1 is accessing shared resource." << std::endl;
}
void worker2()
{
std::lock(mutex1, mutex2);
std::lock_guard<std::mutex> lock1(mutex1, std::adopt_lock);
std::lock_guard<std::mutex> lock2(mutex2, std::adopt_lock);
// 对共享资源进行访问
std::cout << "Worker 2 is accessing shared resource." << std::endl;
}
int main()
{
std::thread t1(worker1);
std::thread t2(worker2);
t1.join();
t2.join();
return 0;
}
scoped_lock与lock_guard等价,但是可以管理多个锁,由于是RAII类型,比std::lock方便。
#include <mutex>
#include <thread>
#include <iostream>
std::mutex mu1;
std::mutex mu2;
void worker1()
{
std::scoped_lock lock(mu1, mu2);
std::cout << "worker1 locked mu1 and mu2\n";
// do some work
}
void worker2()
{
std::scoped_lock lock(mu1, mu2);
std::cout << "worker2 locked mu1 and mu2\n";
// do some work
}
int main()
{
std::thread t1(worker1);
std::thread t2(worker2);
t1.join();
t2.join();
return 0;
}
条件变量
条件变量condition_variable,用于通知其他等待锁的线程,节省性能。
条件变量会加锁和解锁,所以这里使用了 unique_lock。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool flag = false;
void producer() {
std::unique_lock<std::mutex> lock(mtx);
std::cout << "Producer thread started" << std::endl;
// 假设在这里进行一些计算
// ...
flag = true; // 修改共享状态
cv.notify_one(); // 通知等待的线程
}
void consumer() {
std::unique_lock<std::mutex> lock(mtx);
std::cout << "Consumer thread started" << std::endl;
while (!flag) { // 如果共享状态的值不满足条件,则等待
cv.wait(lock);
}
std::cout << "Consumer thread ended" << std::endl;
}
int main() {
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.join();
return 0;
}
读写锁
读写锁shared_mutex是区别互斥锁的更细颗粒度的锁。因为只有写会触发竞态,所以读写锁的原理是只有写的时候才只允许单线程访问,而互斥锁是读写都只有一个线程才能访问。
写线程加独占锁unique_lock,读线程加共享锁shared_lock。
#include <iostream>
#include <shared_mutex>
#include <thread>
#include <vector>
std::shared_mutex mtx; // 定义共享锁
void read_func(int id) {
std::shared_lock<std::shared_mutex> lock(mtx); // 读操作加共享锁
std::cout << "Reader thread " << id << " read." << std::endl;
}
void write_func(int id) {
std::unique_lock<std::shared_mutex> lock(mtx); // 写操作加独占锁
std::cout << "Writer thread " << id << " write." << std::endl;
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i) {
if (i % 2 == 0) {
threads.emplace_back(read_func, i);
} else {
threads.emplace_back(write_func, i);
}
}
for (auto& thread : threads) {
thread.join();
}
return 0;
}
future库
async
thread线程是没有返回值的,所以想返回值只能通过全局变量。
async的优势是新线程可以返回值,并使用局部变量接收。
#include <iostream>
#include <future>
int func(int x) {
return x * 2;
}
int main() {
//在函数开始就执行子线程,返回值储存在result里
std::future<int> result = std::async(std::launch::async, func, 10);
std::cout << "做其他事..." << std::endl;
// 获取子线程的返回值,使用局部变量res接收,如果此时子进程还没有执行完,则继续等待子进程。
int res = result.get();
std::cout << "Result: " << res << std::endl;
return 0;
}
package_task
package_task是async的底层,与async不同的是,async是函数,直接返回future值,package_task是类,需要先创建packaged_task对象,然后packaged_task对象执行计算返回future值,最后future值提取目标值。
所以async可以打包任务结果值future,而packaged_task可以打包任务packaged_task。
#include <iostream>
#include <future>
#include <chrono>
int func(int n) {
std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟函数执行需要1秒钟的时间
return n + 1;
}
int main() {
std::packaged_task<int(int)> task(func); // 将函数func及其参数绑定到packaged_task对象中
std::future<int> fut = task.get_future(); // 获得与task相关联的future对象
std::thread t(std::move(task), 1); // 在另一个线程中执行任务
t.detach(); // 分离线程,使其在后台运行
std::cout << "Waiting for result..." << std::endl;
int result = fut.get(); // 等待任务完成并获取结果
std::cout << "Result: " << result << std::endl;
return 0;
}
并行算法
C++17.
内存模型
为什么需要内存模型?
在单核单进程的时代,程序是这样被优化的:
- 编译器优化,产生乱序指令,原本A定义在B之前,但是为了某种优化,B被放在了A之前;
- CPU乱序执行,为了提高指令速度;
- CPU多级缓存,提高数据的读写速度。
编译器优化
编译前:
int A, B;
void foo()
{
A = B + 1;
B = 0;
}
编译后:
int A, B;
void foo()
{
int temp = B;
B = 0;
A = temp + 1;
}
为此编译器提供了关键字volatile,用来阻止优化:
int A, B;
void foo()
{
A = B + 1;
asm volatile("" ::: "memory");
B = 0;
}
CPU乱序执行
CPU为了提高运行效率,提供了乱序执行,当然CPU也提供了阻止乱序执行的方法:
lfence (asm), void _mm_lfence(void)
sfence (asm), void _mm_sfence(void)
mfence (asm), void _mm_mfence(void)
CPU多级缓存
现代CPU都提供了多级缓存策略,每个CPU内核都有自己的缓存,在并发编程中,如果Core1的数据只放在了L1缓存中,那么Core2-Core4就都不能看见数据的变更,因为他们无法访问Core1的L1缓存。
原子类型
原子类型包括:
类型别名 | 类型定义 |
---|---|
atomic_bool | std::atomic<bool> |
atomic_char | std::atomic<char> |
atomic_schar | std::atomic<signed char> |
atomic_uchar | std::atomic<unsigned char> |
atomic_int | std::atomic<int> |
atomic_uint | std::atomic<unsigned> |
atomic_short | std::atomic<short> |
atomic_ushort | std::atomic<unsigned short> |
atomic_long | std::atomic<long> |
atomic_ulong | std::atomic<unsigned long> |
atomic_llong | std::atomic<long long> |
atomic_ullong | std::atomic<unsigned long long> |
atomic_char16_t | std::atomic<char16_t> |
atomic_char32_t | std::atomic<char32_t> |
atomic_wchar_t | std::atomic<wchar_t> |
原子类型不能使用常规的赋值方式,需要提供特殊的方法来执行:
内存模型
内存模型提供了进制被优化的参数:
- seq-cst 模型,顺序一致性,不允许被优化;
- acq-rel 模型,
其他
glibc pthread库:
话说有跨平台库,就没必要用系统级库函数了吧。
#include <pthread>
pthread_t t = pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);
Windows 线程库:
CreateThread();