CMCore/inc/hgl/thread/SwapColl.h

157 lines
3.5 KiB
C
Raw Normal View History

2019-08-19 19:19:58 +08:00
#ifndef HGL_THREAD_SWAP_LIST_INCLUDE
#define HGL_THREAD_SWAP_LIST_INCLUDE
#include<hgl/thread/ThreadMutex.h>
#include<hgl/thread/Semaphore.h>
2025-04-23 00:29:44 +08:00
#include<hgl/type/ArrayList.h>
2019-08-19 19:19:58 +08:00
#include<hgl/type/Set.h>
namespace hgl
{
/**
*
*/
template<typename T,template<typename> class S> class SwapColl
{
protected:
S<T> join_list;
S<T> proc_list;
ThreadMutex lock;
public:
virtual ~SwapColl(){}
/**
*
*/
bool Add(T &item)
{
lock.Lock();
int result=join_list.Add(item);
lock.Unlock();
return(result!=-1);
}
/**
*
*/
int Add(T *item_list,const int count)
{
lock.Lock();
int result=join_list.Add(item_list,count);
lock.Unlock();
return result;
}
/**
* 使
*/
S<T> &GetProcList()
{
lock.Lock();
proc_list.Add(join_list);
join_list.Clear();
2019-08-19 19:19:58 +08:00
lock.Unlock();
return proc_list;
}
S<T> *operator ->(){return &proc_list;}
operator S<T> &(){return proc_list;}
};//template<typename T> class SwapColl
2025-04-23 00:21:59 +08:00
template<typename T> using SwapList=SwapColl<T,ArrayList>; ///<安全交换列表
2019-08-19 19:19:58 +08:00
template<typename T> using SwapSet=SwapColl<T,Set>; ///<安全交换集合
/**
*
*/
template<typename T,template<typename> class S> class SemSwapColl
{
protected:
S<T> join_list;
S<T> proc_list;
ThreadMutex lock;
Semaphore sem;
public:
virtual ~SemSwapColl()=default;
/**
*
*/
bool Add(T &item)
{
lock.Lock();
int result=join_list.Add(item);
lock.Unlock();
if(result!=-1)
sem.Post(1);
return(result!=-1);
}
/**
*
*/
int Add(T *item_list,const int count)
{
lock.Lock();
int result=join_list.Add(item_list,count);
lock.Unlock();
if(result>0)
sem.Post(1);
return result;
}
/**
*
*/
bool WaitProc(const double time_out=HGL_TIME_ONE_MINUTE)
{
if(!sem.Acquire(time_out))
return(false);
lock.Lock();
proc_list.Add(join_list);
join_list.Clear();
2019-08-19 19:19:58 +08:00
lock.Unlock();
return(true);
}
/**
*
*/
bool TryProc()
{
if(!sem.TryAcquire())
return(false);
lock.Lock();
proc_list.Add(join_list);
join_list.Clear();
2019-08-19 19:19:58 +08:00
lock.Unlock();
return(true);
}
S<T> *operator ->(){return &proc_list;}
operator S<T> &(){return proc_list;}
};//template<typename T> class SemSwapColl
2025-04-23 00:21:59 +08:00
template<typename T> using SemSwapList=SemSwapColl<T,ArrayList>; ///<安全信号交换列表
2019-08-19 19:19:58 +08:00
template<typename T> using SemSwapSet=SemSwapColl<T,Set>; ///<安全信号交换集合
}//namespace hgl
#endif//HGL_THREAD_SWAP_LIST_INCLUDE