Skip to content

Instantly share code, notes, and snippets.

@vk2gpu
Last active January 2, 2020 13:21
Show Gist options
  • Save vk2gpu/7f8e55e984bf3a13e96992e7832599b2 to your computer and use it in GitHub Desktop.
Save vk2gpu/7f8e55e984bf3a13e96992e7832599b2 to your computer and use it in GitHub Desktop.
eilogd@NEILO-MBA:~/Dev/test$ g++ test.cpp -O0 -o test -l pthread
neilogd@NEILO-MBA:~/Dev/test$ ./test
Expected value: 4000000
Non-volatile: 1530233
Volatile: 1362100
Atomic: 4000000
neilogd@NEILO-MBA:~/Dev/test$ ./test
Expected value: 4000000
Non-volatile: 1308157
Volatile: 1371573
Atomic: 4000000
neilogd@NEILO-MBA:~/Dev/test$ ./test
Expected value: 4000000
Non-volatile: 1949115
Volatile: 1374197
^[[AAtomic: 4000000
neilogd@NEILO-MBA:~/Dev/test$ ./test
Expected value: 4000000
Non-volatile: 2241178
Volatile: 1937355
Atomic: 4000000
neilogd@NEILO-MBA:~/Dev/test$
neilogd@NEILO-MBA:~/Dev/test$ g++ test.cpp -O3 -o test -l pthread
neilogd@NEILO-MBA:~/Dev/test$ ./test
Expected value: 4000000
Non-volatile: 3000000
Volatile: 2097256
Atomic: 4000000
neilogd@NEILO-MBA:~/Dev/test$ ./test
Expected value: 4000000
Non-volatile: 3000000
Volatile: 1162799
Atomic: 4000000
neilogd@NEILO-MBA:~/Dev/test$ ./test
Expected value: 4000000
Non-volatile: 3000000
Volatile: 958987
Atomic: 4000000
neilogd@NEILO-MBA:~/Dev/test$ ./test
Expected value: 4000000
Non-volatile: 3000000
Volatile: 1858777
Atomic: 4000000
neilogd@NEILO-MBA:~/Dev/test$
#include <thread>
#include <atomic>
#include <functional>
#include <condition_variable>
#include <cstdio>
#include <vector>
static int test0 = {};
static volatile int test1 = {};
static std::atomic<int> test2 = {};
static std::atomic<bool> begin_check = {};
static const int num_incs = 1000000;
static const int num_thread = 4;
static const int expected_result = num_incs * num_thread;
using jobfn = std::function<void()>;
jobfn test0_job()
{
begin_check.store(false);
return []()
{
while(!begin_check.load());
for(int i = 0; i < num_incs; ++i)
test0++;
};
}
jobfn test1_job()
{
begin_check.store(false);
return []()
{
while(!begin_check.load());
for(int i = 0; i < num_incs; ++i)
test1++;
};
}
jobfn test2_job()
{
begin_check.store(false);
return []()
{
while(!begin_check.load());
for(int i = 0; i < num_incs; ++i)
test2++;
};
}
void run_test(jobfn job)
{
std::vector<std::thread> threads;
for(int i = 0; i < num_thread; ++i)
{
threads.push_back(std::thread(job));
}
begin_check.store(true);
for(int i = 0; i < num_thread; ++i)
{
threads[i].join();
}
}
int main(int, char**)
{
printf("Expected value: %i\n", expected_result);
run_test(test0_job());
printf("Non-volatile: %i\n", test0);
run_test(test1_job());
printf("Volatile: %i\n", test1);
run_test(test2_job());
printf("Atomic: %i\n", test2.load());
return 0;
}
Copy link

ghost commented Jan 2, 2020

Very nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment