Skip to content

Instantly share code, notes, and snippets.

@aont
Created October 2, 2011 06:46
Show Gist options
  • Select an option

  • Save aont/1257151 to your computer and use it in GitHub Desktop.

Select an option

Save aont/1257151 to your computer and use it in GitHub Desktop.
atomic
#include <sys/time.h>
#include <iostream>
#include <vector>
#include <boost/format.hpp>
#include <omp.h>
//#define MP_CRITICAL
//#define MP_ATOM
#define GCC_ATOM
template<typename T>
T atom_inc(volatile T* addr)
{
while(true) {
const T oldval = *addr;
if(__sync_val_compare_and_swap(addr, oldval, oldval+1))
return oldval;
}
}
template<typename T>
T atom_inc(T& obj) { atom_inc(&obj); }
int main()
{
const std::size_t omp_num_threads = omp_get_max_threads();
std::vector<std::size_t> count_vec(omp_num_threads);
std::cerr << boost::format("num_threads:\t%d") % omp_num_threads << std::endl;
const std::size_t num_count = 1024*1024;
struct timeval start_time, end_time;
gettimeofday(&start_time, NULL);
#pragma omp parallel
{
const std::size_t omp_thread_num = omp_get_thread_num();
#pragma omp for
for(std::ptrdiff_t t=0; t<num_count; ++t) {
#if defined(GCC_ATOM)
atom_inc(count_vec[omp_thread_num]);
#else
#if defined(MP_ATOM)
#pragma omp atomic
#elif defined(MP_CRITICAL)
#pragma omp critical
#endif
++count_vec[omp_thread_num];
#endif
}
}
gettimeofday(&end_time, NULL);
const double elapsed_time
= ( end_time.tv_sec - start_time.tv_sec )
+ (end_time.tv_usec - start_time.tv_usec) * 1e-6;
std::cerr << boost::format("time:\t%f") % elapsed_time << std::endl;
for(std::size_t t=0; t<omp_num_threads; ++t) {
std::cerr << boost::format("%d\t%d") % t % count_vec[t] << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment