C++标准库中的多线程编程

1、线程类

std::thread是一切多线程的基础,可以使用全局函数,类的静态函数、类成员函数和Lambda匿名函数作为线程入口。

void GlobalFunc(float s)
{
    std::cout << "GlobalFunc: " << s << std::endl;
}

class Student
{
public:   
    static std::string GetTeacher(int i)
    {
        std::cout << "Teacher Name: " << teacherName << std::endl;
        return teacherName;
    }
    std::string GetName(float s)
    {
        std::cout << "Student Name: " << name << std::endl;
        return name;
    }
private:
    int age = 20;
    std::string name = "lilei";
    static std::string teacherName;
};
std::string Student::teacherName = "Lucy";

int main()
{
    using namespace std;
    Student a;   
    thread th(GlobalFunc, 3.14159); //全局函数
    thread th1(Student::GetTeacher,2); //静态类函数
    thread th2(&Student::GetName,&a, 2.5); //成员函数
    thread th3([&a](int m) { a.GetName(m); },5);

    th.join();
    th1.join();
    th2.join();
    th3.join();  
}

2、互斥量

互斥量为多线程环境下保护共享数据而设计,通常共享数据只在同时读取的情况下是安全的。读-写和同时写可能造成数据不完整。需要对共享数据进行独占式访问。

2.1 互斥量基本操作

互斥量有lock上锁和unlock解锁两个最基本的操作。几种互斥量如下:

//互斥量
std::mutex m_lock;
std::shared_mutex sm_lock;
std::recursive_mutex rm_lock;

//带超时功能的互斥量
std::timed_mutex tm_lock;
std::recursive_timed_mutex rtm_lock;
std::shared_timed_mutex stm_lock;

2.2 递归互斥量

递归锁主要用于解决同一个线程多次对同一互斥量进行上锁操作导致的死锁问题。

std::recursive_mutex rmu;
std::mutex mu;  //使用普通互斥量,将异常退出

void Task1()
{
    rmu.lock(); //mu.try_lock();
    std::cout << "Task1: " <<  std::endl;   
    rmu.unlock();
}
void Task()
{
    rmu.lock(); //mu.try_lock();
    std::cout << "Task: " << std::endl;
    Task1();
    rmu.unlock();
}

thread th(Task);
th.join();

2.3 带超时互斥量

不带超时功能互斥量调用try_lock将立即返回。带超时功能互斥量包含一个try_lock_for 函数,等待锁直到超时仍未获取锁时函数返回。

创建对象时mutex处于unlock状态。

std::vector<int> shared_data{ 1,2,3,4,5,6,7,8,9,10 };

//互斥量
std::mutex m_lock;
std::shared_mutex sm_lock;
std::recursive_mutex rm_lock;

//带超时功能的互斥量
std::timed_mutex tm_lock;
std::recursive_timed_mutex rtm_lock;
std::shared_timed_mutex stm_lock;

void ModifyShare(int i)
{
	m_lock.lock();
	for (auto& data : shared_data)
	{
		data += i;
	}

	for (auto data : shared_data)
	{
		std::cout << data << " ";
	}
	std::cout << std::endl;
	m_lock.unlock();
}

int main()
{
	std::thread th[10];
	for (int i = 0; i < 10; ++i)
	{
		th[i] = std::thread(ModifyShare, i + 1);
	}
	for (auto& thread : th)
		thread.join();
	return 0;
}

2.4 读共享互斥量

多个线程读取共享数据不会导致等待,写操作等待。有写入操作时,阻塞其他读写操作。

std::shared_mutex smu;

std::vector<int> shared_data{ 1,2,3,4,5,6,7,8,9,10 };

void ReadTask()
{
    smu.lock_shared(); 
    std::cout << "ReadTask: " << std::this_thread::get_id()<< std::endl;
    for (const auto& data : shared_data)
        std::cout << data << " ";
    std::cout << std::endl; 
    smu.unlock_shared();
    
}
void WriteTask()
{
    smu.lock(); //mu.try_lock();
    std::cout << "WriteTask: " << std::endl;  
    for (auto& data : shared_data)
    {
        data++;        
    }
    smu.unlock();
}

 smu.lock_shared() 锁定后会阻塞 smu.lock(),但不会阻塞其他线程调用smu.lock_shared()获得锁。smu.lock()锁定后会阻塞所有的其他的 smu.lock_shared()和 smu.lock()。可以提高一个生产者多个消费者场景下的读性能。

3、互斥量包装器 

为避免互斥量忘记解锁的情况,对互斥量包装在类对象中,对象创建时上锁,析构时解锁,即使用C++ 的RAII(Resource Acquisition IInitialization)机制。包括std::lock_guard、shared_lock 、 std::unique_lock 、scoped_lock等。

3.1 lock_guard

void ModifyShare(int i)
{
	//std::lock_guard<std::mutex> lockGuard(m_lock);
	std::unique_lock<std::mutex> uniqueLock(m_lock);
	for (auto& data : shared_data)
	{
		data += i;
	}

	for (auto data : shared_data)
	{
		std::cout << data << " ";
	}
	std::cout << std::endl;	
}

3.2 unique_lock

unique_lock 可以手动临时解锁,不必等到对象析构时,常与条件变量配合使用。

    //延迟上锁,构造时不上锁
    std::unique_lock<std::mutex> ulock1(mu, std::defer_lock);    
    if (!ulock1.owns_lock())
    {
        ulock1.lock();
    }

    //构造时假定已经上锁
    std::unique_lock<std::mutex> ulock2(mu, std::adopt_lock);

    //构造时尝试上锁
    std::unique_lock<std::mutex> ulock3(mu, std::try_to_lock);

3.3 shared_lock

shared_lock只会调用读共享互斥量的操作,写操作需要用到unique_lock来上锁。

void ReadTask()
{
    std::shared_lock<std::shared_mutex> sl(smu);
    //smu.lock_shared(); 
    std::cout << "ReadTask: " << std::this_thread::get_id()<< std::endl;
    for (const auto& data : shared_data)
        std::cout << data << " ";
    std::cout << std::endl;
    for (int i = 0; i < 10; i++)
    {
        std::this_thread::sleep_for(1000ms);
        std::cout << std::this_thread::get_id() << std::endl;
    }
    std::cout << std::endl;       
}
void WriteTask()
{
    std::unique_lock<std::shared_mutex> ul(smu);
    std::cout << "WriteTask: " << std::endl;  
    for (auto& data : shared_data)
    {
        data++;        
    }
}

3.4 scoped_lock

避免多个互斥量上锁顺序可能导致的死锁。

std::mutex mu1;
std::mutex mu2;

void Test1()
{
    //mu1.lock();
    //mu2.lock();
    //std::this_thread::sleep_for(1s);
    //mu2.unlock();
    //mu1.unlock();

    //同时获取两个互斥量的锁
    std::scoped_lock sl(mu1, mu2);
    std::this_thread::sleep_for(1s);
}
void Test2()
{
    mu2.lock();
    mu1.lock();
    std::this_thread::sleep_for(1s);
    mu1.unlock();
    mu2.unlock();
}

4、条件变量

条件变量 std::condition_variable 用于线程间通信,通知等待线程继续后续操作。

常用的生产者-(多)消费者场景下,常常使用条件变量。如果你用到了条件变量 std::condition_variable::wait 则必须使用 std::unique_lock 作为参数。那么wait为什么必须使用unique_lock呢? 原因是条件变量在wait时会进行unlock再进入休眠, lock_guard并无该操作接口。

条件变量 std::condition_variable 是为了解决死锁而生,当互斥操作不够用而引入的。 比如,线程可能需要等待某个条件为真才能继续执行, 而一个忙等待循环中可能会导致所有其他线程都无法进入临界区使得条件为真时,就会发生死锁。 所以,condition_variable 实例被创建出现主要就是用于唤醒等待线程从而避免死锁。 std::condition_variable的 notify_one() 用于唤醒一个线程; notify_all() 则是通知所有线程。

#include <mutex>
#include <shared_mutex>
#include <random>

using namespace std::chrono_literals;

std::mutex m_lock;
std::shared_mutex smu;
std::condition_variable cv;
std::list<int> shared_data;

void Producer()
{
	std::random_device r;
	// Choose a random mean between 1 and 6
	std::default_random_engine e1(r());

	while (true)
	{
		std::uniform_int_distribution<int> uniform_dist(1, 6);
		int mean = uniform_dist(e1);
		std::unique_lock<std::mutex> uniqueLock(m_lock);
		shared_data.push_back(mean);		
		uniqueLock.unlock();		
		cv.notify_one();
		std::this_thread::sleep_for(1s);
	}
}

void Consumer()
{
	while (true)
	{
		std::this_thread::sleep_for(100ms);
		std::unique_lock<std::mutex> uniqueLock(m_lock);
		//wait函数执行前,已经获取到 m_lock 锁。
		//wait收到信号先解锁,判断条件成立则上锁返回,否则返回继续等待信号
		cv.wait(uniqueLock, []() { return !shared_data.empty(); });
		if (!shared_data.empty())
		{
			auto data = shared_data.front();
			shared_data.pop_front();
			std::cout <<std::this_thread::get_id()<< " : " << data << std::endl;
		}
	}
}

int main()
{
	//并发线程数=CPU逻辑核心数量
	auto cpuCoreCount = std::thread::hardware_concurrency();

	std::thread pro(Producer);
	std::thread consu1(Consumer);
	std::thread consu2(Consumer);
	pro.join();
	consu1.join();
	consu2.join();
	return 0;
}

wait: 调用时先释放锁,再休眠等待唤醒信号。如果线程被唤醒或者超时那么会先进行lock获取锁, 再判断条件(传入的参数)是否成立, 如果成立则 wait函数返回,不成立则释放锁继续休眠。

5、线程间传递数据

5.1 Future/Promise模型

std::promise 线程通过set_value将数据存入promise对象(只能调用一次),其他线程需要数据时,通过promise对象对应的std::future函数get来异步获取该值(只能调用一次),未设置值时线程会阻塞。它提供了一种主线程和工作者线程间数据传输的机制。

void Producer ( std::promise<int> p, int i)
{
	++i;
	p.set_value(i);
	std::this_thread::sleep_for(3s);
	std::cout << "exit " << std::endl;
}

int main()
{
	std::promise<int> p;
	auto f = p.get_future();
	std::thread pro(Producer,move(p), 5);
	pro.detach();
	std::cout << "result: " << f.get() << std::endl;
	std::this_thread::sleep_for(5s);
	return 0;
}

5.2 打包任务

std::packaged_task将各类可调用对象(函数、Lambda表达式,仿函数等)包装成对象,将函数调用和返回值获取进行拆分。

int Producer (int i)
{
	++i;
	std::this_thread::sleep_for(2s);
	std::cout << "task" << std::endl;
	return i;
}

int main()
{
	std::packaged_task<int(int)> task(Producer);	
	auto f = task.get_future();
	//同步调用
	//task(5); 
	//异步调用
	std::thread t(std::move(task),100);
	t.detach();
	
	std::cout << "wait for result " << std::endl;
	f.wait(); //阻塞线程等待处理完成
	//if (f.wait_for(100ms) == std::future_status::ready)
		std::cout << "result: " << f.get() << std::endl;
	std::this_thread::sleep_for(5s);
	return 0;
}

5.3 异步函数

std::async 函数可以替代thread。std::launch::deferred方式,在获取值的时候,同步调用函数。默认方式是启动一个独立的线程。

int Producer (int i)
{
	++i;	
	std::cout << "task: " << std::this_thread::get_id() << std::endl;
	std::this_thread::sleep_for(2s);
	return i;
}

int main()
{
	//延迟调用函数,不创建线程
	auto f = std::async(std::launch::deferred, Producer, 5);
	//创建线程
	//auto f = std::async(std::launch::async,Producer, 5);
	
	//f.wait();
	//if (f.wait_for(100ms) == std::future_status::ready)
	std::this_thread::sleep_for(1000ms);
	std::cout << std::this_thread::get_id() << " : wait for result " << std::endl;
	std::cout << "result: " << f.get() << std::endl;
	
	std::this_thread::sleep_for(5s);
	return 0;
}

5.5 for_each算法

C++17中重载了算法std::for_each,新增对容器中每个元素进行并行处理能力。

	std::vector<int> s{ 1,3,2,5,7 };
	std::for_each(s.begin(), s.end(), [](int i) {std::cout << i << " "; });
	std::cout << std::endl;
	int output[5] = {};

	//每个元素创建一个线程处理
	std::for_each(std::execution::par, s.begin(), s.end(),
		[&](auto& i) {
			
			int index = &i - s.data();
			output[index] = i * i;
		});

6、Sender/Recevier模型

即将进入C++26的异步并发调度模型,std::execution,使用sender、receiver、scheduler

P2300提案:

P2300R5: `std::execution` (open-std.org)https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2300r5.htmlNVIDIA的参考实现:

GitHub - NVIDIA/stdexec: `std::execution`, the proposed C++ framework for asynchronous and parallel programming.https://github.com/NVIDIA/stdexec
 

 作者介绍:

What are Senders Good For, Anyway? – Eric Nieblerhttps://ericniebler.com/2024/02/04/what-are-senders-good-for-anyway/

参考资料:

Execution library - cppreference.comhttps://en.cppreference.com/w/cpp/experimental/execution

示例程序HelloWorld:

#include <cstdio>
#include <execution>
#include <string>
#include <thread>
#include <utility>
using namespace std::literals;
 
int main()
{
    std::execution::run_loop loop;
 
    std::jthread worker([&](std::stop_token st)
    {
        std::stop_callback cb{ st, [&]{ loop.finish(); }};
        loop.run();
    });
 
    std::execution::sender auto hello = std::execution::just("hello world"s);
    std::execution::sender auto print
        = std::move(hello)
        | std::execution::then([](std::string msg)
        {
            std::puts(msg.c_str());
            return 0;
        });
 
    std::execution::scheduler auto io_thread = loop.get_scheduler();
    std::execution::sender auto work = std::execution::on(io_thread, std::move(print));
 
    auto [result] = std::this_thread::sync_wait(std::move(work)).value();
 
    return result;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值