我想创建一个有/没有线程安全的池。我不想定义互斥体字段,如果池不是线程安全的,所以我使用了 std::conditional,但是因为它没有完全按照我想要的方式进行操作,并且创建了两个“类型”选项,所以我选择了“int8 (char)” “作为钝化互斥体类型。(相反,我希望整个定义消失)
template<typename T, bool threadSafe = true>
class Pool
{
private:
//Mutex mutex; this is the field i want it to be DISAPPEARED, i modified it as below
std::conditional<threadSafe, Mutex, int8>::type mutex;
protected:
static constexpr item_type_size_datatype TypeSizeX = sizeof(T) + sizeof(size_t);
public:
Pool(size_t clusterItemCount) : ClusterItemCount(clusterItemCount),
ClusterByteSize(clusterItemCount* TypeSizeX)
{
#ifdef CriticalSection
if constexpr (threadSafe)
InitializeCriticalSection(&mutex);
#endif
}
~Pool()
{
Clear();
#ifdef CriticalSection
if constexpr (threadSafe)
DeleteCriticalSection(&mutex);
#endif
}
T* Occupy(bool& outFirstTime)
{
if constexpr (threadSafe)
{
MutexLock(mutex);
}
//do the occupation
if constexpr (threadSafe)
{
MutexUnlock(mutex);
}
return result;
}
};
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,在方法内部我使用了“constexpr if”,它的作用就像一个魅力,因为它禁用了整个代码块。
主要问题:是否有更好的方法来禁用整个定义,例如“Mutex mutex;” 除了“std::条件”之外
附加问题:我收到“int8 mutex”的“未初始化变量”警告,我必须用“0”初始化..如何在编译时以“std::conditional”方式执行此操作。
这可以通过模板专门化来实现,例如:
template<bool threadSafe>
class PoolBase;
template<>
class PoolBase<false>
{// empty
};
template<>
class PoolBase<true>
{
protected: Mutex m_mutex;
};
template<typename T, bool threadSafe = true>
class Pool: private PoolBase<threadSafe>
{
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
134 次 |
| 最近记录: |