c++多线程,锁

1)机器最大线程数
uint16_t max_thread = thread::hardware_concurrency();

2)vector中管理线程
获取线程id
a)thread::id _id=std::this_thread::get_id();
b)thread th(getSum_vector, ref(arr), ref(_sum));
cout << th.get_id();
容器中存储线程变量:使用emplace_back原位构造
a) vector _vector(10);
for (int i = 0; i < 2; i++)
{
_vector.emplace_back(getSum_vector, ref(arr), ref(_sum));

}
  1. std::thread
    使用std::thread()创建线程对象
    a)std::thread th(function,avg)
    b)std::thread th(&class::function,,&类实例,avg)
    c)std::thread th(std::bind(&class::function,,&类实例,avg))
    d)std::thread th{{过程}}
    如果function需要引用类型参数,则使用ref()

4)线程等待/分离
创建后需要手动join/detach
或使用RAII机制,在离开作用域时自动分离


class Thread_Guard {
public:
	Thread_Guard(std::thread& _th):th(_th)
	{
		std::cout << "call";
	}

	~Thread_Guard()
	{
		if (th.joinable())
			th.join();
		else {
		
		}
		std::cout << "Thread_Guard diaoy endding" << std::endl;
	}
private:
	std::thread& th;


};

5)锁类型
std::lock_guardstd::mutex _guard
std::unique_lock独占锁
std::share_lock共享锁
std::scoped_lock (c++17)同时获得锁

6)锁

//同时加锁
std::mutex _mutex1;
std::mutex _mutex2;
//使用lock()同时加锁
std::lock(_mutex1, _mutex2);
std::lock_guardstd::mutex(_mutex1, std::adopt_lock);
std::lock_guardstd::mutex(_mutex2, std::adopt_lock);
//std::adopt_lock 是一个标记,告诉 std::lock_guard 它应该采用已经锁定的互斥锁,而不是再次尝试锁定它。

7)共享锁std::share_lock
场景:写操作需要独占锁。而读操作需要共享锁。
std::share_mutex(c++17),C++11标准没有共享互斥量,可以使用boost提供的boost::shared_mutex

8)层级锁,递归锁

posted on   不败剑坤  阅读(22)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 三行代码完成国际化适配,妙~啊~
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示