简体   繁体   中英

What is the memory footprint of std::atomic in C++11, in practice?

A program that I am writing needs to store significant amounts of data (several gigabytes) in ram to be accessed atomically by many threads. std::atomic seems to be a reasonable way to do this, because its accesses are likely to be more efficient than wrapping all accesses in one or more std::mutex s, since, worst case, it will use a mutex internally and be equivalent.

My data is organized as a set of Chunk objects, which have, among others, an array member containing most of their data. Right now, I am thinking about defining it as std::array<std::atomic<unsigned int>, SOME_CONSTANT_HERE> , but this is only going to be efficient if the memory footprint of std::atomic on built-in types such as unsigned int is no worse than unsigned int itself, for, based on my calculations, with the amount of data I need to store, current common ram capacities are barely sufficient.

The only alternative that I see (other alternatives are welcome) is to have each chunk have its own std::mutex instance, but that is problematic because often threads will need to work with several chunks at the same time (not nearly all, however), and holding multiple locks is both problematic for deadlocks, and will cause significant contention due to the patterns of which chunks are accessed by various threads.

So, what is the memory footprint in practice on x86_64 of std::atomic for integral types?

EDIT: I tried searching around on Google, and even a bit of digging in the GNU standard library source, to no avail.

You can check it yourself here: https://godbolt.org/g/6zjJCU - with no optimization turned on, both std::atomic and a regular variable take the same amount of memory.

The difference, however, is the access to the variables. Try to uncomment the block... you get all the static calls and data protection.

If you do a lot of read/writes, a mutex may be more efficient - maybe you can lock the mutex and then read, say, 100 bytes of data? Also, be careful for dirty reads/writes: if you read an atomic, do something with the value, and then try to update the atomic, interleaved thread may have already changed the atomic's value. This can easily be avoided with a slightly more costly mutex.

According to this reference atomic has a single member of the template type. It also has a specialization for unsigned int , though it doesn't provide that much over the basic type. Memory-wise you should be OK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM