C++11標準下我們可以更加簡單地調用線程,但是線程調用就必須注意對象線程安全的問題。
我們可以用智能指針簡單地去解決對象線程安全問題,我嘗試瞭解什麼叫智能指針,但是最後由於腦子不夠用壓根不懂他在說什麼鬼,所以我嘗試自己寫個線程安全的容器。
這個線程容器使用的是C++11的一些新特性去實現的,所以不要嘗試用VC6神器去編譯。
首先需要用到模板類而不是繼承,因爲使用模板才能確保我不用再去爲這件破事而煩惱。
CSafeMap.hpp
#include <functional>
#include <mutex>
#include <map>
using namespace std;
typedef enum {
em不存在該對象 = 0,
em對象使用中 = 1,
em對象空閒 = 2,
em調用對象成功 = 2
}enCSafeMapStatus;//定義個枚舉狀態
template<class T1>
class CSafeObject
{
public:
CSafeObject() { m_Mark = em不存在該對象; }
CSafeObject(const CSafeObject& cc) { *this = cc; }
virtual ~CSafeObject(void) { }
public:
bool CreateObject(std::function<bool(T1&)> Func)
{
std::lock_guard<std::mutex> hold(m_mtx);
if(m_Mark != em不存在該對象)//避免重複創建對象
return true;
bool bret = Func(m_data );
if(bret )
m_Mark = em對象空閒;
return bret ;
}
void CtrlItem(std::function<void(T1&)> Func)
{
bool bret = false;
do
{
{
std::lock_guard<std::mutex> hold(m_mtx);
if (m_Mark == em不存在該對象)return;//因爲對象隨時會被釋放
if (m_Mark != em對象空閒) continue;//等候對象空閒,如果代碼寫得足夠坑爹就會在這裏死鎖,測試的時候可以引入個計時器來退出,而release時就不要了。
m_Mark = em對象使用中;//修改狀態計數
}
Func(m_data);
//調用對象
{
std::lock_guard<std::mutex> hold(m_mtx);
m_Mark = em對象空閒;//修改狀態計數
}
bret = true;
} while (bret == false);
}
void Delete(std::function<void(T1&)> Func = [](T1&itr) {if (itr)delete itr; itr = nullptr; })
{
bool bret = false;
do
{
{
std::lock_guard<std::mutex> hold(m_mtx);
if (m_Mark == em不存在該對象)return;
if (m_Mark != em對象空閒) continue;
m_Mark = em對象使用中;
}
Func(m_data);
{
std::lock_guard<std::mutex> hold(m_mtx);
m_Mark = em不存在該對象;//修改狀態計數-宣佈死亡
}
bret = true;
} while (bret == false);
}
private:
T1 m_data;//需要在多個線程中使用到的對象
int m_Mark;//狀態計數器
std::mutex m_mtx;//鎖
};
....
例子:
int main()
{
CSafeObject<CString> strData;
strData.CreateObject([](CString&tm)->bool {
tm = _T("");
return true;
});
thread th1([&]() {
do
{
strData.CtrlItem([](CString&tm) {
tm+=_T("Fu*k thread !");
});
this_thread::sleep_for(chrono::microseconds(1));
} while (1);
});
thread th2([&]() {
do
{
strData.CtrlItem([](CString&tm) {
tm.Empty();
});
this_thread::sleep_for(chrono::microseconds(2));
} while (1);
});
thread th3([&]() {
do
{
strData.CtrlItem([](CString&tm) {
tm+=_T("I love you!");
});
this_thread::sleep_for(chrono::microseconds(3));
} while (1);
});
thread th4([&]() {
do
{
strData.CtrlItem([](CString&tm) {
NowLogStringEx(_T("say:%s"), tm);
});
this_thread::sleep_for(chrono::microseconds(4));
} while (1);
});
th1.detach();
th2.detach();
th3.detach();
th4.detach();
......
strData.Delete([](CString&itr){});//釋放對象,因爲不是new出來的所以在這裏載入一個函數釋放對象
}
...
這個容器很賤單,就是鎖上對象然後操作對象,這裏我使用了模板類,std::function,std::mutex,std::lock_guard和Lambel表達式去實現這個線程安全的模板。如果我們使用多個對象時這個類的簡便性就越明顯,畢竟不在需要去擔心鎖有沒有釋放,那一把鎖負責那個變量的問題,不過需要注意的是不要嵌套使用CtrlItem,需要調用到多個對象的時候應使用拷貝對象的方式即:
CString str1;
strData_1.CtrlItem([](CString&tm) {str1 =tm;});
strData_2.CtrlItem([](CString&tm) { tm
=
str1;});
#pragma once
#include <queue>
#include <mutex>
using namespace std;
#ifndef logStrNor
#define logStrNor(str,...) {if (m_log) {CString strData; strData.Format(str, __VA_ARGS__); m_log->MarkDown(L"Normal", strData);}}
#endif
template<class T1>
class CSafeItems
{
public:
CSafeItems() { }
CSafeItems(const CSafeItems& cc) { *this = cc; }
virtual ~CSafeItems(void) { }
public:
int FillItems(int nCount, std::function<T1()> Func){
std::lock_guard<std::mutex> hold(m_mtx);
for (int n = 0; n < nCount; n++){
auto itr = Func();
if (itr){
m_data.push(itr);
m_nMax++;
}
}
return m_data.size();
}
void CtrlItem(std::function<void(T1&)> Func)
{
bool bret = false;
do
{
T1 t1;
{
std::lock_guard<std::mutex> hold(m_mtx);
if (m_data.size() == 0)continue;
t1 = m_data.front();
m_data.pop();
}
Func(t1);
{
std::lock_guard<std::mutex> hold(m_mtx);
m_data.push(t1);
}
bret = true;
} while (bret == false);
}
void UpdateItem(std::function<void(T1&)> Func, std::function<void()> FuncFinished)
{
do {
{
std::lock_guard<std::mutex> hold(m_mtx);
if (m_nMax == m_data.size())
{
queue<T1> data = m_data;
while (m_mark.size()) { m_data.pop(); }
while (data.size()) {
auto itr = data.front();
Func(itr);
m_data.push(itr);
data.pop();
}
FuncFinished();
break;
}
}
::Sleep(1);
} while (1);
}
void RemoveAll()
{
do {
{
std::lock_guard<std::mutex> hold(m_mtx);
if (m_nMax == m_data.size())
{
while (m_mark.size())
{
m_data.pop();
}
break;
}
}
::Sleep(1);
} while (1);
}
void DeleteAll(std::function<void(T1&)> Func = [](T1&itr) {if (itr)delete itr; itr = nullptr; })
{
do {
{
std::lock_guard<std::mutex> hold(m_mtx);
if (m_nMax == m_data.size())
{
while (m_data.size())
{
auto itr = m_data.front();
Func(itr);
m_data.pop();
}
break;
}
}
::Sleep(1);
} while (1);
}
int GetSize()
{
std::lock_guard<std::mutex> hold(m_mtx);
return m_count.size();
}
private:
queue<T1> m_data;
std::mutex m_mtx;
int m_nMax;
};
#define def原子操作(x) \
{ \
int n = 0; \
while (lock_stream->test_and_set()) { \
if(n==0)logStrNor(_T("def原子操作waitting %s "), m_strMark);n++;\
}\
x; \
lock_stream->clear(); \
if(n>0){ logStrNor(_T("def原子操作end %s %d"), m_strMark, n-1); } \
}
#define CONNECTION(text1,text2) text1##text2
#define CONNECT(text1,text2) CONNECTION(text1,text2)
#define INITATOM(tm) \
{ \
static std::atomic_flag CONNECT(CONNECT(lock_,tm),__LINE__) = ATOMIC_FLAG_INIT; \
tm.Init(#tm,&CONNECT(CONNECT(lock_,tm),__LINE__)); \
}
static int nTick = 0;
#include <atomic>
template<class T1>
class CAtomicObject
{
public:
CAtomicObject() { m_strMark = _T(""); }
CAtomicObject(const CAtomicObject& cc) { *this = cc; }
virtual ~CAtomicObject(void) { }
void Init(CString strMark, std::atomic_flag*lock) {
m_strMark.Format(_T("%s_%d05%d"), strMark, GetTickCount(),nTick++);
lock_stream = lock;
}
public:
void CreateObject(std::function<T1()> Func)
{
def原子操作(m_data = Func())
}
bool CreateObject(std::function<bool(T1&)> Func)
{
bool bret;
def原子操作( bret = Func(m_data))
return bret;
}
bool CreateObject(CString strMark,std::function<bool(T1&)> Func)
{
Init(strMark);
def原子操作(bret = Func(m_data))
return bret;
}
void CtrlItem(std::function<void(T1&)> Func)
{
def原子操作( Func(m_data))
}
void Delete(std::function<void(T1&)> Func = [](T1&itr) {if (itr)delete itr; itr = nullptr; })
{
def原子操作( Func(m_data))
}
private:
T1 m_data;
std::atomic_flag*lock_stream;
CString m_strMark;
};