amputate src/base/simple_mutex.h

Use standard mutex instead
This commit is contained in:
Aliaksey Kandratsenka 2024-02-04 21:07:17 +00:00
parent 885dd867bc
commit 2e5ecb4de6
9 changed files with 39 additions and 384 deletions

View File

@ -1260,7 +1260,6 @@ if(GPERFTOOLS_BUILD_CPU_PROFILER)
src/base/commandlineflags.h
src/base/googleinit.h
src/base/logging.h
src/base/simple_mutex.h
src/base/sysinfo.h
${SPINLOCK_INCLUDES}
${LOGGING_INCLUDES})

View File

@ -1259,7 +1259,6 @@ S_CPU_PROFILER_INCLUDES = src/profiledata.h \
src/base/commandlineflags.h \
src/base/googleinit.h \
src/base/logging.h \
src/base/simple_mutex.h \
src/base/sysinfo.h \
$(SPINLOCK_INCLUDES) \
$(LOGGING_INCLUDES)

View File

@ -1,330 +0,0 @@
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
// Copyright (c) 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---
// Author: Craig Silverstein.
//
// A simple mutex wrapper, supporting locks and read-write locks.
// You should assume the locks are *not* re-entrant.
//
// To use: you should define the following macros in your configure.ac:
// ACX_PTHREAD
// AC_RWLOCK
// The latter is defined in ../autoconf.
//
// This class is meant to be internal-only and should be wrapped by an
// internal namespace. Before you use this module, please give the
// name of your internal namespace for this module. Or, if you want
// to expose it, you'll want to move it to the Google namespace. We
// cannot put this class in global namespace because there can be some
// problems when we have multiple versions of Mutex in each shared object.
//
// NOTE: TryLock() is broken for NO_THREADS mode, at least in NDEBUG
// mode.
//
// CYGWIN NOTE: Cygwin support for rwlock seems to be buggy:
// http://www.cygwin.com/ml/cygwin/2008-12/msg00017.html
// Because of that, we might as well use windows locks for
// cygwin. They seem to be more reliable than the cygwin pthreads layer.
//
// TRICKY IMPLEMENTATION NOTE:
// This class is designed to be safe to use during
// dynamic-initialization -- that is, by global constructors that are
// run before main() starts. The issue in this case is that
// dynamic-initialization happens in an unpredictable order, and it
// could be that someone else's dynamic initializer could call a
// function that tries to acquire this mutex -- but that all happens
// before this mutex's constructor has run. (This can happen even if
// the mutex and the function that uses the mutex are in the same .cc
// file.) Basically, because Mutex does non-trivial work in its
// constructor, it's not, in the naive implementation, safe to use
// before dynamic initialization has run on it.
//
// The solution used here is to pair the actual mutex primitive with a
// bool that is set to true when the mutex is dynamically initialized.
// (Before that it's false.) Then we modify all mutex routines to
// look at the bool, and not try to lock/unlock until the bool makes
// it to true (which happens after the Mutex constructor has run.)
//
// This works because before main() starts -- particularly, during
// dynamic initialization -- there are no threads, so a) it's ok that
// the mutex operations are a no-op, since we don't need locking then
// anyway; and b) we can be quite confident our bool won't change
// state between a call to Lock() and a call to Unlock() (that would
// require a global constructor in one translation unit to call Lock()
// and another global constructor in another translation unit to call
// Unlock() later, which is pretty perverse).
//
// That said, it's tricky, and can conceivably fail; it's safest to
// avoid trying to acquire a mutex in a global constructor, if you
// can. One way it can fail is that a really smart compiler might
// initialize the bool to true at static-initialization time (too
// early) rather than at dynamic-initialization time. To discourage
// that, we set is_safe_ to true in code (not the constructor
// colon-initializer) and set it to true via a function that always
// evaluates to true, but that the compiler can't know always
// evaluates to true. This should be good enough.
//
// A related issue is code that could try to access the mutex
// after it's been destroyed in the global destructors (because
// the Mutex global destructor runs before some other global
// destructor, that tries to acquire the mutex). The way we
// deal with this is by taking a constructor arg that global
// mutexes should pass in, that causes the destructor to do no
// work. We still depend on the compiler not doing anything
// weird to a Mutex's memory after it is destroyed, but for a
// static global variable, that's pretty safe.
#ifndef GOOGLE_MUTEX_H_
#define GOOGLE_MUTEX_H_
#include <config.h>
#if defined(NO_THREADS)
typedef int MutexType; // to keep a lock-count
#elif defined(_WIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN // We only need minimal includes
# endif
// We need Windows NT or later for TryEnterCriticalSection(). If you
// don't need that functionality, you can remove these _WIN32_WINNT
// lines, and change TryLock() to assert(0) or something.
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0400
# endif
# include <windows.h>
typedef CRITICAL_SECTION MutexType;
#elif defined(HAVE_RWLOCK)
// Needed for pthread_rwlock_*. If it causes problems, you could take it
// out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it
// *does* cause problems for FreeBSD, or MacOSX, but isn't needed
// for locking there.)
# ifdef __linux__
# define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls
# endif
# include <pthread.h>
typedef pthread_rwlock_t MutexType;
#else
# include <pthread.h>
typedef pthread_mutex_t MutexType;
#endif
#include <assert.h>
#include <stdlib.h> // for abort()
#define MUTEX_NAMESPACE perftools_mutex_namespace
namespace MUTEX_NAMESPACE {
class Mutex {
public:
// This is used for the single-arg constructor
enum LinkerInitialized { LINKER_INITIALIZED };
// Create a Mutex that is not held by anybody. This constructor is
// typically used for Mutexes allocated on the heap or the stack.
inline Mutex();
// This constructor should be used for global, static Mutex objects.
// It inhibits work being done by the destructor, which makes it
// safer for code that tries to acqiure this mutex in their global
// destructor.
inline Mutex(LinkerInitialized);
// Destructor
inline ~Mutex();
inline void Lock(); // Block if needed until free then acquire exclusively
inline void Unlock(); // Release a lock acquired via Lock()
inline bool TryLock(); // If free, Lock() and return true, else return false
// Note that on systems that don't support read-write locks, these may
// be implemented as synonyms to Lock() and Unlock(). So you can use
// these for efficiency, but don't use them anyplace where being able
// to do shared reads is necessary to avoid deadlock.
inline void ReaderLock(); // Block until free or shared then acquire a share
inline void ReaderUnlock(); // Release a read share of this Mutex
inline void WriterLock() { Lock(); } // Acquire an exclusive lock
inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock()
private:
MutexType mutex_;
// We want to make sure that the compiler sets is_safe_ to true only
// when we tell it to, and never makes assumptions is_safe_ is
// always true. volatile is the most reliable way to do that.
volatile bool is_safe_;
// This indicates which constructor was called.
bool destroy_;
inline void SetIsSafe() { is_safe_ = true; }
// Catch the error of writing Mutex when intending MutexLock.
Mutex(Mutex* /*ignored*/) {}
// Disallow "evil" constructors
Mutex(const Mutex&);
void operator=(const Mutex&);
};
// Now the implementation of Mutex for various systems
#if defined(NO_THREADS)
// When we don't have threads, we can be either reading or writing,
// but not both. We can have lots of readers at once (in no-threads
// mode, that's most likely to happen in recursive function calls),
// but only one writer. We represent this by having mutex_ be -1 when
// writing and a number > 0 when reading (and 0 when no lock is held).
//
// In debug mode, we assert these invariants, while in non-debug mode
// we do nothing, for efficiency. That's why everything is in an
// assert.
Mutex::Mutex() : mutex_(0) { }
Mutex::Mutex(Mutex::LinkerInitialized) : mutex_(0) { }
Mutex::~Mutex() { assert(mutex_ == 0); }
void Mutex::Lock() { assert(--mutex_ == -1); }
void Mutex::Unlock() { assert(mutex_++ == -1); }
bool Mutex::TryLock() { if (mutex_) return false; Lock(); return true; }
void Mutex::ReaderLock() { assert(++mutex_ > 0); }
void Mutex::ReaderUnlock() { assert(mutex_-- > 0); }
#elif defined(_WIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Mutex::Mutex() : destroy_(true) {
InitializeCriticalSection(&mutex_);
SetIsSafe();
}
Mutex::Mutex(LinkerInitialized) : destroy_(false) {
InitializeCriticalSection(&mutex_);
SetIsSafe();
}
Mutex::~Mutex() { if (destroy_) DeleteCriticalSection(&mutex_); }
void Mutex::Lock() { if (is_safe_) EnterCriticalSection(&mutex_); }
void Mutex::Unlock() { if (is_safe_) LeaveCriticalSection(&mutex_); }
bool Mutex::TryLock() { return is_safe_ ?
TryEnterCriticalSection(&mutex_) != 0 : true; }
void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks
void Mutex::ReaderUnlock() { Unlock(); }
#elif defined(HAVE_RWLOCK)
#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
if (is_safe_ && fncall(&mutex_) != 0) abort(); \
} while (0)
Mutex::Mutex() : destroy_(true) {
SetIsSafe();
if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
}
Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) {
SetIsSafe();
if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
}
Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_rwlock_destroy); }
void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); }
void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); }
bool Mutex::TryLock() { return is_safe_ ?
pthread_rwlock_trywrlock(&mutex_) == 0 : true; }
void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); }
void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); }
#undef SAFE_PTHREAD
#else
#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
if (is_safe_ && fncall(&mutex_) != 0) abort(); \
} while (0)
Mutex::Mutex() : destroy_(true) {
SetIsSafe();
if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
}
Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) {
SetIsSafe();
if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
}
Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_mutex_destroy); }
void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock); }
void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock); }
bool Mutex::TryLock() { return is_safe_ ?
pthread_mutex_trylock(&mutex_) == 0 : true; }
void Mutex::ReaderLock() { Lock(); }
void Mutex::ReaderUnlock() { Unlock(); }
#undef SAFE_PTHREAD
#endif
// --------------------------------------------------------------------------
// Some helper classes
// MutexLock(mu) acquires mu when constructed and releases it when destroyed.
class MutexLock {
public:
explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); }
~MutexLock() { mu_->Unlock(); }
private:
Mutex * const mu_;
// Disallow "evil" constructors
MutexLock(const MutexLock&);
void operator=(const MutexLock&);
};
// ReaderMutexLock and WriterMutexLock do the same, for rwlocks
class ReaderMutexLock {
public:
explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); }
~ReaderMutexLock() { mu_->ReaderUnlock(); }
private:
Mutex * const mu_;
// Disallow "evil" constructors
ReaderMutexLock(const ReaderMutexLock&);
void operator=(const ReaderMutexLock&);
};
class WriterMutexLock {
public:
explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); }
~WriterMutexLock() { mu_->WriterUnlock(); }
private:
Mutex * const mu_;
// Disallow "evil" constructors
WriterMutexLock(const WriterMutexLock&);
void operator=(const WriterMutexLock&);
};
// Catch bug where variable name is omitted, e.g. MutexLock (&mu);
#define MutexLock(x) static_assert(0)
#define ReaderMutexLock(x) static_assert(0)
#define WriterMutexLock(x) static_assert(0)
} // namespace MUTEX_NAMESPACE
using namespace MUTEX_NAMESPACE;
#undef MUTEX_NAMESPACE
#endif /* #define GOOGLE_SIMPLE_MUTEX_H_ */

View File

@ -32,31 +32,24 @@
// Author: llib@google.com (Bill Clarke)
#include "config_for_unittests.h"
#include <assert.h>
#include <stdio.h>
#ifdef HAVE_MMAP
#include <sys/mman.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for sleep()
#endif
#include <algorithm>
#include <string>
#include <vector>
#include <mutex>
#include <thread>
#include <chrono>
#include <gperftools/malloc_hook.h>
#include "malloc_hook-inl.h"
#include "base/logging.h"
#include "base/simple_mutex.h"
#include "base/sysinfo.h"
#include "base/threading.h"
#include "tests/testutil.h"
// On systems (like freebsd) that don't define MAP_ANONYMOUS, use the old
// form of the name instead.
#ifndef MAP_ANONYMOUS
# define MAP_ANONYMOUS MAP_ANON
#endif
namespace {
std::vector<void (*)()> g_testlist; // the tests to run
@ -80,14 +73,6 @@ static int RUN_ALL_TESTS() {
return 0;
}
void Sleep(int seconds) {
#ifdef _MSC_VER
_sleep(seconds * 1000); // Windows's _sleep takes milliseconds argument
#else
sleep(seconds);
#endif
}
using base::internal::kHookListMaxValues;
// Since HookList is a template and is defined in malloc_hook.cc, we can only
@ -242,21 +227,22 @@ void MultithreadedTestThread(TestHookList* list, int shift,
static volatile int num_threads_remaining;
static TestHookList list{kTestValue};
static Mutex threadcount_lock;
static std::mutex threadcount_lock;
void MultithreadedTestThreadRunner(int thread_num) {
// Wait for all threads to start running.
{
MutexLock ml(&threadcount_lock);
std::lock_guard ml{threadcount_lock};
assert(num_threads_remaining > 0);
--num_threads_remaining;
// We should use condvars and the like, but for this test, we'll
// go simple and busy-wait.
while (num_threads_remaining > 0) {
threadcount_lock.Unlock();
Sleep(1);
threadcount_lock.Lock();
threadcount_lock.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
threadcount_lock.lock();
}
}

View File

@ -13,16 +13,16 @@
#include "profile-handler.h"
#include <atomic>
#include <assert.h>
#include <pthread.h>
#include <sys/time.h>
#include <stdint.h>
#include <time.h>
#include <atomic>
#include <mutex>
#include "base/logging.h"
#include "base/simple_mutex.h"
// Some helpful macros for the test class
#define TEST_F(cls, fn) void cls :: fn()
@ -42,15 +42,17 @@ namespace {
std::atomic<intptr_t> allocate_count;
std::atomic<intptr_t> free_count;
// We also "frob" this lock down in BusyThread.
Mutex allocate_lock;
std::mutex allocate_lock;
void* do_allocate(size_t sz) {
MutexLock h(&allocate_lock);
std::lock_guard l{allocate_lock};
allocate_count++;
return malloc(sz);
}
void do_free(void* p) {
MutexLock h(&allocate_lock);
std::lock_guard l{allocate_lock};
free_count++;
free(p);
}
@ -143,17 +145,17 @@ class BusyThread : public Thread {
// Setter/Getters
bool stop_work() {
MutexLock lock(&mu_);
std::lock_guard l{mu_};
return stop_work_;
}
void set_stop_work(bool stop_work) {
MutexLock lock(&mu_);
std::lock_guard l{mu_};
stop_work_ = stop_work;
}
private:
// Protects stop_work_ below.
Mutex mu_;
std::mutex mu_;
// Whether to stop work?
bool stop_work_;
@ -162,7 +164,8 @@ class BusyThread : public Thread {
// malloc locks.
void Run() {
for (;;) {
MutexLock h(&allocate_lock);
std::lock_guard l{allocate_lock};
for (int i = 1000; i > 0; i--) {
if (stop_work()) {
return;

View File

@ -44,15 +44,15 @@
#include <sys/wait.h> // for wait()
#include <atomic>
#include <mutex>
#include "gperftools/profiler.h"
#include "base/simple_mutex.h"
#include "tests/testutil.h"
static std::atomic<int> result;
static int g_iters; // argv[1]
Mutex mutex(Mutex::LINKER_INITIALIZED);
std::mutex mutex;
static void test_other_thread() {
#ifndef NO_THREADS
@ -60,7 +60,7 @@ static void test_other_thread() {
int i, m;
char b[128];
MutexLock ml(&mutex);
std::lock_guard ml(mutex);
for (m = 0; m < 1000000; ++m) { // run millions of times
for (i = 0; i < g_iters; ++i ) {
result ^= i;
@ -75,7 +75,7 @@ static void test_other_thread() {
static void test_main_thread() {
int i, m;
char b[128];
MutexLock ml(&mutex);
std::lock_guard ml(mutex);
for (m = 0; m < 1000000; ++m) { // run millions of times
for (i = 0; i < g_iters; ++i ) {
result ^= i;

View File

@ -78,12 +78,14 @@
#include <malloc.h> // defines pvalloc/etc on cygwin
#endif
#include <assert.h>
#include <vector>
#include <algorithm>
#include <string>
#include <mutex>
#include <new>
#include <string>
#include <vector>
#include "base/logging.h"
#include "base/simple_mutex.h"
#include "gperftools/malloc_hook.h"
#include "gperftools/malloc_extension.h"
#include "gperftools/nallocx.h"
@ -373,7 +375,7 @@ class TesterThread {
int generation; // Generation counter of object contents
};
Mutex lock_; // For passing in another thread's obj
std::mutex lock_; // For passing in another thread's obj
int id_; // My thread id
AllocatorState rnd_; // For generating random numbers
vector<Object> heap_; // This thread's heap
@ -503,10 +505,10 @@ class TesterThread {
const int tid = rnd_.Uniform(FLAGS_numthreads);
TesterThread* thread = threads[tid];
if (thread->lock_.TryLock()) {
if (thread->lock_.try_lock()) {
// Pass the object
thread->passed_.push_back(object);
thread->lock_.Unlock();
thread->lock_.unlock();
heap_size_ -= object.size;
heap_[index] = heap_[heap_.size()-1];
heap_.pop_back();
@ -520,11 +522,11 @@ class TesterThread {
// objects into a local vector.
vector<Object> copy;
{ // Locking scope
if (!lock_.TryLock()) {
if (!lock_.try_lock()) {
return;
}
swap(copy, passed_);
lock_.Unlock();
lock_.unlock();
}
for (int i = 0; i < copy.size(); ++i) {

View File

@ -249,7 +249,6 @@
<ClInclude Include="..\..\src\base\googleinit.h" />
<ClInclude Include="..\..\src\base\linked_list.h" />
<ClInclude Include="..\..\src\base\logging.h" />
<ClInclude Include="..\..\src\base\mutex.h" />
<ClInclude Include="..\..\src\base\spinlock.h" />
<ClInclude Include="..\..\src\base\spinlock_internal.h" />
<ClInclude Include="..\..\src\base\spinlock_linux-inl.h" />

View File

@ -172,9 +172,6 @@
<ClInclude Include="..\..\src\windows\mini_disassembler_types.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\src\base\mutex.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\src\packed-cache-inl.h">
<Filter>Header Files</Filter>
</ClInclude>