This question is related to my previous. I did some tests and figured out that having array full of atomics is much MUCH faster than my previous approach with mutexes. But is it ok to have millions of them? Maybe there's something I simply don't know?
-
1Something like - "it's the same as having an array of ints, so use it". Or "on Intel Core i7 there's a special registers for atomics and in case of the overflow the PC will explode, so don't use it".– nikitablackJan 25, 2016 at 12:16
-
2One way to investigate: You should write two almost identical, minimal test programs, which manipulate an array. One test program using just plain integer, another with atomics, doing exact same thing. Then compile them to assembler output, and compare the generated code.– hydeJan 25, 2016 at 12:20
-
1There is no way to answer this question without a well-defined metric for goodness. You need to provide significantly more hardware and software detail.– Jeff HammondJan 25, 2016 at 12:42
-
1An array of atomics is often a bad idea, you will get false sharing– Jonathan WakelyJan 25, 2016 at 13:07
-
1@nikitablack, if you had a single mutex protecting a huge array of ints then you had explicit sharing: you were making every thread wait while another thread updated any int at all. Is it "false" when it's done so explicitly? An array of atomics means that only ints on the same cache-line will cause other threads to wait. That might be better, but still involves waiting while some unrelated int gets updated. That can be avoided by padding each element to the cacheline size, but that wastes a lot of memory (unless you can put other useful data in the padding that won't cause false sharing).– Jonathan WakelyJan 25, 2016 at 14:45
1 Answer
There's nothing special about the storage of an atomic intrinsic. What's special about it are:
The instructions emitted to access the data to ensure that different threads see memory updates in the correct order, and
The compiler (and indeed the processor) is not allowed to re-order instructions so that a release operation happens before a store operation when that was not the author's intent (and vice versa).
A million std::atomic<int>
s will not consume any more resources than the memory required to represent them. Your code will issue a lot of memory fence or acquire/release operations while accessing them, but it would if you used a mutex too, since blocks of code protected by a mutex have the same restrictions vis-a-vis observed order of updates across threads.
-
1I guess on some architecture there may be more stringent alignment requirements (say, to have efficient atomic semantics only integers aligned on 16-byte boundaries may be used), so such an array may take more space than an array of plain
int
s; in practice, I don't know of any such platform. Jan 25, 2016 at 12:46 -
-