std::mutex互斥量的应用

35 篇文章 2 订阅


一、mutex互斥量

互斥量是在多线程并发中避免数据竞争的一种锁。
它有三个常用函数:

  1. lock() 加锁
  2. unlock() 解锁
  3. try_lock() 尝试加锁(不阻塞)

二、使用示例

#include <iostream>
#include <mutex>
#include <vector>
#include <string>
#include <ctime>
#include <thread>

using namespace std;

// 时间模拟消息
string mock_msg()
{
	char buff[64] = { 0 };
	time_t time_result = time(nullptr);
	tm tm;
	localtime_s(&tm, &time_result);
	strftime(buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", &tm);
	return buff;
}

class CMutexTest
{
public:
	void recv_msg(); //接收消息
	void read_msg(); //处理消息
private:
	vector<string> msg_queue; //消息队列
	mutex m_mutex;	//互斥量
};

// 模拟接收消息
void CMutexTest::recv_msg()
{
	while (true)
	{
		string msg = mock_msg();
		cout << "recv the msg " << msg << endl;

		// 消息添加到队列
		m_mutex.lock();
		msg_queue.push_back(msg);
		m_mutex.unlock();
	}
}

// 模拟读取处理
void CMutexTest::read_msg()
{
	// 尝试加锁
	if (m_mutex.try_lock())
	{
		// 加锁成功
		if (!msg_queue.empty())
		{
			// 处理消息并移除
			string msg = msg_queue.front();
			cout << "read the msg " << msg << endl;
			msg_queue.erase(msg_queue.begin());
		}
		m_mutex.unlock();
	}
	else
	{
		// 加锁失败
		this_thread::sleep_for(chrono::seconds(1));
	}
}

int main()
{
	CMutexTest my_test;
	thread recv_thread(&CMutexTest::recv_msg, &my_test); //接收线程
	thread read_thread(&CMutexTest::read_msg, &my_test); //处理线程

	recv_thread.join();
	read_thread.join();
} 

三、总结

互斥量是C++多线程编程中非常基础的一个知识点,它的lock是阻塞的,而try_lock是非阻塞的会立即返回。在实际应用中要考虑不同场景来选择使用,对于线程中有其他任务要处理的应考虑选择非阻塞的try_lock。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值