C++多线程学习(十四、细粒度锁队列)

细粒度锁队列是针对于对象进行一个加锁的过程。

细粒度锁队列是一种并发编程中常用的同步机制,用于解决多线程竞争问题,通过将一个共享资源划分为多个较小的部分,并为每个部分分配一个独立的锁来实现并发控制。

创建细粒度锁队列需要按照共享资源的逻辑结构进行划分,并为每个部分分配一个独立的锁。

可以通过自定义锁对象或者使用并发集合类中提供的锁来实现。

主要用途是提高并发性能。

在多线程环境中,当多个线程同时访问同一个共享资源时,会引发竞争条件,导致性能下降和数据不一致的问题。使用细粒度锁队列可以将资源的竞争范围缩小到更小的部分,减少了线程之间的竞争,提高了并发性能。

细粒度锁队列的使用场景包括但不限于以下几种情况:
1. 频繁访问的共享资源较多,使用粗粒度锁会导致过多的线程竞争,使用细粒度锁可以减小竞争范围,提高并发性能。
2. 共享资源的操作可以被并行进行,但是使用粗粒度锁会导致串行执行,使用细粒度锁可以让多个线程并发执行,提高吞吐量。
3. 共享资源的数据结构支持细粒度的操作,例如链表、哈希表等,通过细粒度锁队列可以实现更灵活和高效的并发控制。

综上所述,细粒度锁队列可以提高并发性能和吞吐量,减少线程竞争,保证数据的一致性。

但是需要注意的是,使用细粒度锁队列也可能引入额外的开销,导致复杂性增加,需要在实际应用中权衡使用。

简单案例

#include <iostream>
#include <mutex>
#include <thread>
#include <new>
#include <vector>
using namespace std;
template<class T>
class Thread_safe_Quene
{
public:
	Thread_safe_Quene():head(new Node),tail(head.get()){}
	Thread_safe_Quene(const Thread_safe_Quene& other) = delete;
	Thread_safe_Quene& operator=(const Thread_safe_Quene& other) = delete;

	void PushValue(T newValue)
	{
		shared_ptr<T> newData(make_shared<T>(newValue));
		unique_ptr<Node> p(new Node);
		Node* const newTail = p.get();
		lock_guard<mutex> tail_lock();
		tail->data = newData;
		tail->next = move(p);
		tail = newTail;
	}

	shared_ptr<T> tryPop()
	{
		unique_ptr<Node> oldhead = popHead();
		return oldhead ? oldhead->data : shared_ptr<T>();
	}

private:
	struct Node//节点里面用智能指针去进行管理
	{
		shared_ptr<T> data;
		unique_ptr<Node> next;
	};
	//队列的特性是FIFO【先进先出】
	mutex mtx_head;			//表头的互斥量
	mutex mtx_tail;			//表尾的互斥量
	unique_ptr<Node> head;	//记录表头
	Node* tail;				//记录表尾
private:
	Node* getTail()//获取表尾
	{
		lock_guard<mutex> tail_lock(mtx_tail);
		return tail;
	}
	unique_ptr<Node> popHead()//出队,获取表头
	{
		lock_guard<mutex> head_lock(mtx_head);
		if (head.get() == getTail())//空的,无法出队
		{
			return nullptr;
		}
		unique_ptr<Node> oldhead = move(head);
		head = move(oldhead->next);
		return oldhead;
	}
};

void insertData(Thread_safe_Quene<int>& other, int data)
{
	other.PushValue(data);
}
void popData(Thread_safe_Quene<int>& other)
{
	shared_ptr<int> result = other.tryPop();
	if (result==nullptr)
	{
		printf("noValue\n");
	}
	else
	{
		printf("%d\n", *result);
	}
}
int main()
{
	vector<thread> t;
	Thread_safe_Quene<int> test1;
	for (int i =0;i<5000;i++)
	{
		t.push_back(thread(insertData,ref(test1),i));
		t.push_back(thread(popData,ref(test1)));
	}
	for (auto& v:t)
	{
		v.join();
	}

	return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

多方通行8

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值