Home >Backend Development >C++ >Does `std::atomic` Use a Hidden Lock and, If So, Where Is It Located?

Does `std::atomic` Use a Hidden Lock and, If So, Where Is It Located?

DDD
DDDOriginal
2024-12-03 21:31:11828browse

Does `std::atomic` Use a Hidden Lock and, If So, Where Is It Located?

Where Does std::atomic Hide Its Lock?

In multi-element data structures, standard atomic types may not always be lock-free. This is attributed to the inability of the CPU to process such data without the assistance of a lock. To illustrate, consider the following example:

#include <iostream>
#include <atomic>

struct foo {
    double a;
    double b;
};

std::atomic<foo> var;

int main()
{
    std::cout << var.is_lock_free() << std::endl;
    std::cout << sizeof(foo) << std::endl;
    std::cout << sizeof(var) << std::endl;
}

Its output for Linux/gcc reveals the following:

0
16
16

Assuming the atomic type and the foo structure occupy the same amount of space, it appears unlikely that a lock is stored in the atomic. But what exactly is the truth behind this conundrum?

Lock Location and Implications for Multiple Instances

The customary approach involves employing a hash table of mutexes (or spinlocks) keyed to the address of the atomic object. This hash function favors the lowest bits of the address as an index into an array of size 2^n.

Ore else, the LLVM std::atomic implementation incorporates higher address bits to prevent automatic aliasing. This ensures that objects separated by a significant power of 2 are not mapped to the same lock.

Importantly, atomic objects only operate in a lock-free manner when shared in memory between distinct processes, where each process is equipped with its own hash table of locks.

Collisions within the hash table may warrant caution. While this poses no correctness issue, it could harm performance by fostering contention among multiple threads. However, this is a relatively infrequent occurrence, as lock-free atomic objects are typically favored on platforms of concern.

Regarding deadlocks, rest assured that this is not a concern as std::atomic functions refrain from acquiring locks on multiple objects simultaneously. Consequently, the library code responsible for lock acquisition never attempts to secure an additional lock while holding an existing one.

The above is the detailed content of Does `std::atomic` Use a Hidden Lock and, If So, Where Is It Located?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn