C++11 下的线程安全模板对象

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





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值