Skip to content

Instantly share code, notes, and snippets.

@takaswie
Created July 30, 2017 05:47
Show Gist options
  • Save takaswie/e98c12b91e6bdaa409226eea8c44dcf0 to your computer and use it in GitHub Desktop.
Save takaswie/e98c12b91e6bdaa409226eea8c44dcf0 to your computer and use it in GitHub Desktop.
Nowadays, arithmetic operations for storage classes of any sizes are not necessarily compiled and executed as atomic instruction.
#include<iostream>
#include<atomic>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<mutex>
/*
* Refereces:
* - std::unique_lock: https://cpprefjp.github.io/reference/mutex/unique_lock.html
* - std:condition_variable: http://ja.cppreference.com/w/cpp/thread/condition_variable
* - std::mutex: https://cpprefjp.github.io/reference/mutex/mutex.html
* - std::thread: https://cpprefjp.github.io/reference/thread/thread.html
* - random: https://cpprefjp.github.io/reference/thread/thread.html
* - https://www.ibm.com/developerworks/jp/linux/library/l-posix3/index.html
* - https://fossies.org/dox/glibc-2.25/atomic_8h.html
* - http://qiita.com/termoshtt/items/c01745ea4bcc89d37edc
* - http://torini.hateblo.jp/entry/2014/08/08/003352
* - https://cpplover.blogspot.jp/2013/11/blog-post_4069.html
* - An overview to polyhedral model: https://www.cs.indiana.edu/~achauhan/Teaching/B629/2010-Fall/StudentPresns/PolyhedralModelOverview.pdf
*/
constexpr std::size_t TH_MAX = 16 * 16 * 16;
constexpr std::size_t WEIGHT = 100;
//constexpr std::size_t TH_MAX = 16;
//constexpr std::size_t WEIGHT = 1;
#ifdef ATOMIC
using Mode = std::atomic<int>;
#else
using Mode = int;
#endif
struct Sync{};
struct NoSync{};
using syncQ = Sync;
// コンパイル時評価
/*
template<typename T>
void tasks_sync(auto i){ }
*/
// 評価されない
template<typename T>
void tasks_sync(decltype(TH_MAX)& i){}
template<>
void tasks_sync<Sync>(decltype(TH_MAX)& i){
while(i < TH_MAX){
std::this_thread::yield();
}
}
/*
template<typename T>
void tasks_sync(decltype(TH_MAX)* i){ }
template<>
void tasks_sync<Sync>(decltype(TH_MAX)* i){
while(*i < TH_MAX){
std::this_thread::yield();
}
}
*/
template<typename T>
int target(void){
T ctr;
ctr = 0;
std::thread tasks[TH_MAX];
for(auto i = decltype(TH_MAX)(0); i < TH_MAX; i++)
{
tasks[i] = std::thread([&]()
{
tasks_sync<syncQ>(i);
//tasks_sync<syncQ>(&i);
for(auto j = decltype(WEIGHT)(0);j++ < WEIGHT;) {
ctr-=1;
ctr+=2;
}
});
}
for(auto i = decltype(TH_MAX)(0); i < TH_MAX; i++){
tasks[i].join();
}
std::cout << TH_MAX * WEIGHT << " ?=? "<< ctr << std::endl;
return 0;
}
int main(void){
target<Mode>();
// target();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment