0
点赞
收藏
分享

微信扫一扫

std::mutex互斥量的应用

小云晓云 2022-04-05 阅读 76
c++

std::mutex互斥量的应用


一、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 条评论