c++ 线程安全的string类

非安全string

说明

c++标准未规定stl容器以及字符串的线程安全性,故std::string在多线程下是不安全的。

代码示例

#include <iostream>
#include <stdio.h>
using namespace std;

std::string *sp = nullptr;

void Read()
{
	for(int i = 0; i < 100000; i++)
	{
		std::string  s = "";
		s = *sp;
	}
}

void Write()
{
	for(int i = 0; i < 100000; i++)
	{
		*sp = std::to_string(i);
	}
}

int main()
{
	while(1)
	{
		sp = new std::string("string test");
		std::thread t1(Read);
		std::thread t2(Write);
		t1.join();
		t2.join();
		delete sp;
		sp = nullptr;
	}

	return 0;
}

安全string

安全string类封装

  • 使用std::recursive_mutex递归锁保证string多线程下的读写安全;

关于std::recursive_mutex,可以查看:https://blog.csdn.net/www_dong/article/details/132197541

class TSString 
{
	typedef std::lock_guard<std::recursive_mutex> RecursiveGuard;
	mutable std::recursive_mutex rmutex;   // 注意增加mutable修饰
	std::string str_;

public:
	TSString() {}

	TSString(const TSString& str)
	{
		Set(str.Get());
	}

	TSString& operator= (const TSString& str)
	{
		if(this == &str)
			return *this;

		Set(str.Get());
		return *this;
	}

	void Set(const char* str)
	{
		RecursiveGuard mtx(rmutex);
		if(NULL == str)
		{
			str_ = "";
		}
		else
		{
			str_ = str;
		}
	}

	void Set(const std::string& str)
	{
		RecursiveGuard mtx(rmutex);
		str_ = str;
	}

	std::string Get() const
	{
		std::string str;
		{	
			RecursiveGuard mtx(rmutex);
			str = str_;
		}

		return str;
	}

	int Compare(const char* str) const 
	{
		if(NULL == str)
			return 1;

		RecursiveGuard mtx(rmutex);
		return str_.compare(str);
	}

	int Compare(const std::string& str) const
	{
		return Compare(str.c_str());
	}

	int Compare(const TSString& s) const
	{
		return Compare(s.Get());
	}	
};

代码示例

TSString *sp = nullptr;

void Read()
{
	for(int i = 0; i < 5000; i++)
	{
		TSString s;
		s.Set("");
		s = *sp;
	}
}

void Write()
{
	for(int i = 0; i < 5000; i++)
	{
		sp->Set(std::to_string(i));
	}
}

int main()
{
	while(1)
	{
		TSString s;
		s.Set("string test");
		sp = new TSString(s);
		std::thread t1(Read);
		std::thread t2(Write);
		t1.join();
		t2.join();
		delete sp;
		sp = nullptr;
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值