1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
///
/// @file OmpLock.hpp
/// @brief The OmpLock and LockGuard classes are RAII-style
/// wrappers for OpenMP locks.
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef OMPLOCK_HPP
#define OMPLOCK_HPP
#include <macros.hpp>
#include <primecount-config.hpp>
#if defined(_OPENMP)
#include <omp.h>
#else
// If OpenMP is disabled we define the functions used by
// the OmpLock and LockGuard classes as no-op.
namespace {
using omp_lock_t = int;
inline void omp_init_lock(omp_lock_t*) { }
inline void omp_destroy_lock(omp_lock_t*) { }
inline void omp_set_lock(omp_lock_t*) { }
inline void omp_unset_lock(omp_lock_t*) { }
} // namespace
#endif
namespace primecount {
struct OmpLock
{
void init(int threads)
{
ASSERT(!is_initialized());
ASSERT(threads > 0);
threads_ = threads;
if (threads_ > 1)
omp_init_lock(&lock_);
}
~OmpLock()
{
if (threads_ > 1)
omp_destroy_lock(&lock_);
}
bool is_initialized() const
{
return threads_ > 0;
}
// 0 = uninitialized lock
unsigned threads_ = 0;
// Use padding to avoid CPU false sharing
MAYBE_UNUSED char pad1[MAX_CACHE_LINE_SIZE];
omp_lock_t lock_;
MAYBE_UNUSED char pad2[MAX_CACHE_LINE_SIZE];
};
class LockGuard
{
public:
LockGuard(OmpLock& lock)
{
ASSERT(lock.is_initialized());
if (lock.threads_ > 1)
{
lock_ = &lock.lock_;
omp_set_lock(lock_);
}
}
~LockGuard()
{
if (lock_)
omp_unset_lock(lock_);
}
private:
omp_lock_t* lock_ = nullptr;
};
} // namespace
#endif
|