当前位置: 首页 > wzjs >正文

做短视频网站用哪家cms网页版百度云

做短视频网站用哪家cms,网页版百度云,十大免费cad制图软件,新手学做网站电子版文章目录 Singleton1 指针版本Version 1 非线程安全版本Version 2 加锁版本Version 3.1 双重检查锁版本 AtomicMutexVersion 3.2 双重检查锁版本 Atomic-onlyVersion 3 两种方式对比 2 引用版本Version 1 简单版本 不推荐Version 2 初始化安全版本Version 3 初始化操作安全版本…

文章目录

  • Singleton
    • 1 指针版本
      • Version 1 非线程安全版本
      • Version 2 加锁版本
      • Version 3.1 双重检查锁版本 Atomic+Mutex
      • Version 3.2 双重检查锁版本 Atomic-only
      • Version 3 两种方式对比
    • 2 引用版本
      • Version 1 简单版本 不推荐
      • Version 2 初始化安全版本
      • Version 3 初始化+操作安全版本
      • Explanation
      • Comparison

Singleton

1 指针版本

Version 1 非线程安全版本

class Logger {
public:static Logger *GetInstance() {if (instance == nullptr) {instance = new Logger();}return instance;}void Log(const std::string &message) {std::cout << message << std::endl;}private:static Logger *instance;Logger() {}
};Logger *Logger::instance = nullptr;

Version 2 加锁版本

增加锁,用于保证线程安全,但是锁开销会影响性能。

class Logger {
public:static Logger *GetInstance() {std::lock_guard<std::mutex> lk(mutex_);if (instance == nullptr) {instance = new Logger();}return instance;}void Log(const std::string &message) {std::cout << message << std::endl;}private:Logger() {}static Logger *instance;static std::mutex mutex_;
};Logger *Logger::instance = nullptr;
std::mutex Logger::mutex_;

Version 3.1 双重检查锁版本 Atomic+Mutex

class Logger {
public:static Logger* GetInstance() {// First, attempt to load the current instance atomicallyLogger* tmp = instance.load(std::memory_order_acquire);// If the instance is nullptr, create itif (tmp == nullptr) {std::lock_guard<std::mutex> lock(mtx);  // Lock only during initializationtmp = instance.load(std::memory_order_relaxed);  // Check again inside the lockif (tmp == nullptr) {tmp = new Logger();  // Create a new instanceinstance.store(tmp, std::memory_order_release);  // Atomically set the instance}}return tmp;}void Log(const std::string& message) {std::cout << message << std::endl;}Logger(const Logger&) = delete;Logger& operator=(const Logger&) = delete;private:Logger() {}  // Private constructor to prevent direct instantiationstatic std::atomic<Logger*> instance;  // Atomic pointer to the Singleton instancestatic std::mutex mtx;  // Mutex to protect initialization
};// Initialize the atomic pointer and mutex
std::atomic<Logger*> Logger::instance(nullptr);
std::mutex Logger::mtx;

Version 3.2 双重检查锁版本 Atomic-only

class Logger {
public:static Logger* GetInstance() {// First, attempt to load the current instance atomicallyLogger* tmp = instance.load(std::memory_order_acquire);// If the instance is nullptr, create itif (tmp == nullptr) {tmp = new Logger();  // Create a new instance// Atomically set the instance if no other thread has done soif (!instance.compare_exchange_strong(tmp, tmp)) {delete tmp; // Another thread won the race, delete the temporary instancetmp = instance.load(std::memory_order_acquire); // Reload the instance}}return tmp;}void Log(const std::string& message) {std::cout << message << std::endl;}Logger(const Logger&) = delete;Logger& operator=(const Logger&) = delete;private:Logger() {}  // Private constructor to prevent direct instantiationstatic std::atomic<Logger*> instance;  // Atomic pointer to the Singleton instance
};// Initialize the atomic pointer to nullptr
std::atomic<Logger*> Logger::instance(nullptr);

Version 3 两种方式对比

  • Only Atomic:

    • Atomic Check: We first check the instance atomically with instance.load. If it’s nullptr, we attempt to create the instance using new.
    • Atomic Set: We use compare_exchange_strong to ensure that only one thread creates the instance. If another thread has already created the instance, it returns the existing one.
    • No Mutex: There is no mutex involved here. The atomic operations ensure thread safety during the initialization phase.
  • Atomic + Mutex:

    • Atomic First Check: The first check of the instance pointer is atomic using instance.load.
    • Mutex Locking: If the instance is nullptr, we lock a mutex (std::mutex mtx) to synchronize access during the actual creation of the instance.
    • Double Check Inside Lock: After acquiring the mutex, we perform another check of the instance. This prevents other threads from creating multiple instances if they were waiting on the mutex.
    • Atomic Set: We use instance.store to atomically set the instance pointer once it’s initialized.

  • Comparison of Effectiveness:
FactorAtomic-onlyAtomic + Mutex
InitializationAtomic operations ensure safe initialization.Mutex ensures exclusive access during initialization.
Post-Initialization AccessLock-free after initialization.Mutex locking still required to access instance.
Performance (High Concurrency)High performance: No lock contention after init.Slower due to mutex locking, even after initialization.
Scalability (Concurrency)Highly scalable: No locks post-initialization.Less scalable: Mutex lock can cause contention.
Memory ConsistencyEnsured via atomic operations and memory_order_acquire/release.Ensured by std::mutex for synchronization.
SimplicitySlightly more complex due to atomic operations.Simpler for developers familiar with mutexes.
  • Atomic-only approach is more effective in high-concurrency environments, especially when you expect many threads accessing the Singleton. Since the initialization is thread-safe and lock-free after the instance is created, it scales much better than the mutex-based approach.

  • Atomic + Mutex approach might be easier to understand for developers familiar with mutexes and might work well in lower-concurrency environments. However, the mutex adds overhead for each access, and if the program has many threads, it will result in contention and slower performance.

  • If you are building a highly concurrent system, prefer the atomic-only approach, as it will perform better with minimal locking overhead.

  • If you have a simpler, lower-concurrency application, using atomic + mutex might be a good trade-off because it provides simplicity and guarantees correct initialization with easy-to-understand synchronization.

2 引用版本

Version 1 简单版本 不推荐

class Logger {
public:static Logger &GetInstance() {return instance;}void Log(const std::string &message) {std::cout << message << std::endl;}private:static Logger instance;Logger() {}
};Logger Logger::instance;

Version 2 初始化安全版本

c++机制保证初始化安全

class Logger {
public:static Logger& GetInstance() {static Logger instance;return instance;}void Log(const std::string &message) {std::cout << message << std::endl;}Logger(const Logger&) = delete;Logger& operator=(const Logger&) = delete;private:Logger() {}
};

Version 3 初始化+操作安全版本

增加操作安全

class Logger {
public:static Logger &GetInstance() {static Logger instance;return instance;}void Log(const std::string &message) {std::lock_guard<std::mutex> lk(mtx);std::cout << message << std::endl;}Logger(const Logger&) = delete;Logger& operator=(const Logger&) = delete;private:Logger() {}std::mutex mtx;
};

Explanation

初始化过程线程安全原因:

  1. Static Local Variable:

    • In the GetInstance() method, we declare a static local variable instance.

      • static Logger instance; ensures that instance is only created once and persists for the entire lifetime of the program.
  2. First-Time Initialization:

    • The first time GetInstance() is called, the static variable instance is initialized. This is where the thread-safety comes into play. The C++11 standard guarantees that the initialization of a static local variable will be thread-safe.
    • If multiple threads try to call GetInstance() simultaneously, only one thread will initialize the instance. The other threads will wait until the initialization is complete, and then they will all see the same instance when they call GetInstance() again.
  3. Thread-Safe Static Initialization:

    • The C++11 guarantee ensures that even if multiple threads try to initialize the instance simultaneously, the static variable will only be initialized once. The other threads will see the already initialized object, which eliminates any race condition.
  4. Post-Initialization Access:

    • After initialization, the reference instance is ready for access, and since it is a static variable, it is always available. There is no locking required for accessing instance after it is initialized, making access very efficient.
  5. No Mutex or Atomic Operations:

    • Since the C++ standard guarantees thread-safe initialization of static local variables, there is no need for additional synchronization mechanisms such as mutexes or atomic operations. The instance is initialized only once, and once it is initialized, it is ready for fast, lock-free access.

Comparison

FactorAtomic-only SingletonAtomic + Mutex SingletonReference Singleton
Thread-Safe InitializationThread-safe initialization using atomic operations.Thread-safe initialization using atomic + mutex locking.Guaranteed thread-safe initialization due to static storage duration in C++11.
Memory ManagementRequires dynamic memory allocation (using new).Requires dynamic memory allocation (using new).No dynamic memory allocation; the instance is static.
Post-Initialization AccessLock-free after initialization, very fast.Mutex still required for each access.Lock-free after initialization, very fast.
Performance (High Concurrency)Very high performance due to lock-free access.Lower performance due to mutex lock overhead.Very high performance with no locking or atomic ops.
Scalability (Concurrency)Highly scalable with minimal contention.Less scalable due to mutex contention.Highly scalable since there’s no contention.
SimplicityMore complex, requires understanding of atomic operations.More complex due to mutex usage and atomic operations.Simpler and more straightforward.
Memory UsageRequires dynamic memory allocation for the Singleton.Requires dynamic memory allocation for the Singleton.No dynamic memory allocation, very efficient.
Lifetime ManagementRequires manual cleanup or reliance on smart pointers.Requires manual cleanup or reliance on smart pointers.Managed automatically by the compiler with static duration.
SafetyThread-safe, but requires careful handling of atomic ops.Thread-safe, but introduces locking overhead.Thread-safe due to the C++ static initialization guarantee, no locking needed.
Use CaseSuitable for high-concurrency, dynamic memory applications where you need to fine-tune memory allocation.Suitable for high-concurrency, but mutex introduces some overhead in high-load
http://www.dtcms.com/wzjs/465210.html

相关文章:

  • 做公司网站要多少钱适合奖励自己的网站免费
  • 厦门网站建设案例今日头条10大新闻
  • jsp网站开发源码实例百度sem运营
  • 如皋市网站建设电子商务网店运营推广
  • 建设局网站瓯龙建州府3号楼电商网站建设方案
  • 医药网站 备案写手接单平台
  • 网站服务器 2核百度一级代理商
  • 上海专业做网站较好的公司百度的营销策略
  • 政府网站建设工作的通知搜狗广告联盟
  • 网站有后台更新不了外包网络推广公司推广网站
  • 用c语言可以做网站吗优化大师免费下载
  • 用dw做网站优化怎么做
  • 服装网站建设目的作用是什么seo外包公司兴田德润
  • 什么样的网站开发比较吃香开发一个网站需要哪些技术
  • 学校网站的平台用途及建设规划免费推广软件
  • 大气wordpress主题南宁seo公司哪家好
  • 线上商城如何推广上海牛巨仁seo
  • 不锈钢公司网站源码 网站建设 产品3级分类asp源码长沙关键词优化方法
  • 安徽网站建设公司百度搜索优化平台
  • 福建省建设行业企业资质查询网站百度seo关键词点击软件
  • 软件下载网站模板网络舆情分析师
  • 东莞网站建设aj工作室站内免费推广有哪些
  • 成都手机网站建设价格最新的国际新闻
  • c 怎么和网站做交互免费建设个人网站
  • 网站代运营收费怎样在百度打广告
  • 强生公司网站建设原则电商平台有哪些?
  • 做相册的网站百度竞价排名案例分析
  • 做付费下载的网站深圳今天重大事件新闻
  • 中国执行信息公开网信息查询网站seo优化徐州百度网络
  • 专门做酒店自助餐的网站十大推广app平台