C++原子与锁

标签 c++ pthreads atomic

假设我有一个 foo 类:

class foo {
    static uint32 count_;
    pthread_mutex_t mu;

    void increase() {
      pthread_mutex_lock(&mu);
      count_++;
      pthread_mutex_unlock(&mu);
    }
}

如果我不使用互斥量,而只是将 std::atomic 作为 count_,会有什么不同吗?

谢谢!

最佳答案

差别很大。 pthread_mutex_lock可能非常昂贵,因为它可能包含系统调用*。原子增量产生 lock xadd .

另一个优势是 std::atomic<...> 可能更好移植,因为它是 C++ 标准的一部分。 Pthread 调用很可能在 Windows 中不起作用。

*) 如果锁已被其他线程持有,则让当前线程休眠。但很可能只有一个 spinlock将会发生。

关于C++原子与锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15102553/

相关文章:

c++ - C++中的动态线程创建

sql - 在不违反约束的情况下交换两个数据库行

c# - C# 合并运算符的原子性

Vulkan 中的 OpenGL GLSL 原子计数器

c++ - Ncurses C++ 打印前景色/背景色交换的文本

c++ - 创建良好的目录结构

c - pthread 程序的臭名昭著的行为

linux - pthread_setaffinity_np : Invalid argument?

c++ - 如何在 XCode 中使用 glew

c++ - C++ 和 C 中的 header 保护