Skip to content

Commit e30f53e

Browse files
committed
cpp: move atomic from cpp-cheat
1 parent 178a668 commit e30f53e

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed

README.adoc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11791,7 +11791,10 @@ The implementation lives under `libgomp` in the GCC tree, and is documented at:
1179111791

1179211792
Programs under link:userland/cpp/[] are examples of link:https://en.wikipedia.org/wiki/C%2B%2B#Standardization[ISO C] programming.
1179311793

11794+
* link:userland/cpp/empty.cpp[]
1179411795
* link:userland/cpp/hello.cpp[]
11796+
* `<atomic>` 32 "Atomic operations library"
11797+
** link:userland/cpp/atomic.cpp[]
1179511798

1179611799
=== POSIX
1179711800

userland/cpp/atomic.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// https://github.com/cirosantilli/linux-kernel-module-cheat#atomic
2+
//
3+
// More restricted than mutex as it can only protect a few operations on integers.
4+
//
5+
// But if that is the use case, may be more efficient.
6+
//
7+
// On GCC 4.8 x86-64, using atomic is a huge peformance improvement
8+
// over the same program with mutexes (5x).
9+
10+
#include <atomic>
11+
#include <cassert>
12+
#include <iostream>
13+
#include <thread>
14+
#include <vector>
15+
16+
#if __cplusplus >= 201103L
17+
std::atomic_ulong my_atomic_ulong(0);
18+
unsigned long my_non_atomic_ulong = 0;
19+
size_t niters;
20+
21+
void threadMain() {
22+
for (size_t i = 0; i < niters; ++i) {
23+
my_atomic_ulong++;
24+
my_non_atomic_ulong++;
25+
}
26+
}
27+
#endif
28+
29+
int main(int argc, char **argv) {
30+
#if __cplusplus >= 201103L
31+
size_t nthreads;
32+
if (argc > 1) {
33+
nthreads = std::stoull(argv[1], NULL, 0);
34+
} else {
35+
nthreads = 2;
36+
}
37+
if (argc > 2) {
38+
niters = std::stoull(argv[2], NULL, 0);
39+
} else {
40+
niters = 1000;
41+
}
42+
std::vector<std::thread> threads(nthreads);
43+
for (size_t i = 0; i < nthreads; ++i)
44+
threads[i] = std::thread(threadMain);
45+
for (size_t i = 0; i < nthreads; ++i)
46+
threads[i].join();
47+
assert(my_atomic_ulong.load() == nthreads * niters);
48+
// Same as above through `operator T`.
49+
assert(my_atomic_ulong == nthreads * niters);
50+
std::cout << my_non_atomic_ulong << std::endl;
51+
#endif
52+
}

userland/cpp/empty.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
// Sanity checking low level stuff, initially inspired by baremetal.
2-
// https://github.com/cirosantilli/linux-kernel-module-cheat#baremetal-cpp
2+
// https://github.com/cirosantilli/linux-kernel-module-cheat#cpp
33

44
int main() {}

0 commit comments

Comments
 (0)