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;
}