mirror of
https://github.com/cirosantilli/linux-kernel-module-cheat.git
synced 2026-01-23 02:05:57 +01:00
c++: move atomic in from cpp-cheat
TODO: README improve, link to x86 LOCK docs
This commit is contained in:
@@ -16,12 +16,31 @@
|
||||
#if __cplusplus >= 201103L
|
||||
std::atomic_ulong my_atomic_ulong(0);
|
||||
unsigned long my_non_atomic_ulong = 0;
|
||||
#if defined(__x86_64__)
|
||||
unsigned long my_arch_atomic_ulong = 0;
|
||||
unsigned long my_arch_non_atomic_ulong = 0;
|
||||
#endif
|
||||
size_t niters;
|
||||
|
||||
void threadMain() {
|
||||
for (size_t i = 0; i < niters; ++i) {
|
||||
my_atomic_ulong++;
|
||||
my_non_atomic_ulong++;
|
||||
#if defined(__x86_64__)
|
||||
__asm__ __volatile__ (
|
||||
"incq %0;"
|
||||
: "+m" (my_arch_non_atomic_ulong)
|
||||
:
|
||||
:
|
||||
);
|
||||
__asm__ __volatile__ (
|
||||
"lock;"
|
||||
"incq %0;"
|
||||
: "+m" (my_arch_atomic_ulong)
|
||||
:
|
||||
:
|
||||
);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -37,7 +56,7 @@ int main(int argc, char **argv) {
|
||||
if (argc > 2) {
|
||||
niters = std::stoull(argv[2], NULL, 0);
|
||||
} else {
|
||||
niters = 1000;
|
||||
niters = 10000;
|
||||
}
|
||||
std::vector<std::thread> threads(nthreads);
|
||||
for (size_t i = 0; i < nthreads; ++i)
|
||||
@@ -45,8 +64,12 @@ int main(int argc, char **argv) {
|
||||
for (size_t i = 0; i < nthreads; ++i)
|
||||
threads[i].join();
|
||||
assert(my_atomic_ulong.load() == nthreads * niters);
|
||||
// Same as above through `operator T`.
|
||||
assert(my_atomic_ulong == nthreads * niters);
|
||||
std::cout << my_non_atomic_ulong << std::endl;
|
||||
// We can also use the atomics direclty through `operator T` conversion.
|
||||
assert(my_atomic_ulong == my_atomic_ulong.load());
|
||||
std::cout << "my_non_atomic_ulong " << my_non_atomic_ulong << std::endl;
|
||||
#if defined(__x86_64__)
|
||||
assert(my_arch_atomic_ulong == nthreads * niters);
|
||||
std::cout << "my_arch_non_atomic_ulong " << my_arch_non_atomic_ulong << std::endl;
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user