标准::原子<uint_least8_t>行为

std::atomic<uint_least8_t> behavior

本文关键字:gt 行为 least8 原子 标准 uint lt      更新时间:2023-10-16

在具有以下功能的系统上:

typedef unsigned char      uint8_t;
typedef unsigned short     uint16_t;
std::atomic<uint8_t>::is_always_lock_free // => false
std::atomic<uint16_t>::is_always_lock_free // => true

据我了解,类型

std::atomic<uint_least8_t>

将是 8 位并且不解锁。

如果是这样,如果我想要一个至少 8 位并且始终无锁的原子类型,我应该写什么?(假设存在此类类型(有没有比以下更好的选择:

std::atomic<
typename std::conditional<
std::atomic<uint8_t>::is_always_lock_free, 
uint8_t, 
uint16_t
>::type
>

(为简单起见,我没有包含未解锁if std::atomic&lt;uint16_t>代码(

好吧,模板的东西有点混乱,但它的用法非常直观:

#include <atomic>
#include <cstdint>
#include <iostream>
template <typename T, typename... others>
class first_lockfree
{
// forward declare internal template
template <bool, typename...> struct cond;
// use this if is_always_lock_free == true
template <typename condT, typename... condTs>
struct cond<true, condT, condTs...>
{
// use first template argument as it is_always_lock_free
using type = condT;
};
// use this if is_always_lock_free == false
template <typename condT, typename... condTs>
struct cond<false, condT, condTs...>
{
// use main template with first template parameter removed
using type = typename first_lockfree<condTs...>::type;
};
public:
using type =typename cond<std::atomic<T>::is_always_lock_free, T, others...>::type;
};

int main(int, char**)
{
using uint8_lockfree_t = first_lockfree<std::uint8_t, std::uint16_t, std::uint32_t, std::uint64_t>::type;
std::cout <<  sizeof(uint8_lockfree_t) << std::endl;
std::cout <<  std::atomic<std::uint8_t>::is_always_lock_free << std::endl;
std::cout <<  std::atomic<std::uint16_t>::is_always_lock_free << std::endl;
std::cout <<  std::atomic<std::uint32_t>::is_always_lock_free << std::endl;
std::cout <<  std::atomic<std::uint64_t>::is_always_lock_free << std::endl;
return 0;
}