gecko-dev/mfbt/ThreadLocal.h

152 lines
3.6 KiB
C
Raw Normal View History

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* Cross-platform lightweight thread local data wrappers. */
#ifndef mozilla_ThreadLocal_h
#define mozilla_ThreadLocal_h
#if defined(XP_WIN)
// This file will get included in any file that wants to add a profiler mark.
// In order to not bring <windows.h> together we could include windef.h and
// winbase.h which are sufficient to get the prototypes for the Tls* functions.
// # include <windef.h>
// # include <winbase.h>
// Unfortunately, even including these headers causes us to add a bunch of ugly
// stuff to our namespace e.g #define CreateEvent CreateEventW
extern "C" {
__declspec(dllimport) void* __stdcall TlsGetValue(unsigned long);
__declspec(dllimport) int __stdcall TlsSetValue(unsigned long, void*);
__declspec(dllimport) unsigned long __stdcall TlsAlloc();
}
#else
# include <pthread.h>
# include <signal.h>
#endif
#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include "mozilla/NullPtr.h"
namespace mozilla {
// sig_safe_t denotes an atomic type which can be read or stored in a single
// instruction. This means that data of this type is safe to be manipulated
// from a signal handler, or other similar asynchronous execution contexts.
#if defined(XP_WIN)
typedef unsigned long sig_safe_t;
#else
typedef sig_atomic_t sig_safe_t;
#endif
/*
* Thread Local Storage helpers.
*
* Usage:
*
* Only static-storage-duration (e.g. global variables, or static class members)
* objects of this class should be instantiated. This class relies on
* zero-initialization, which is implicit for static-storage-duration objects.
* It doesn't have a custom default constructor, to avoid static initializers.
*
* API usage:
*
* // Create a TLS item.
* //
* // Note that init() should be invoked exactly once, before any usage of set()
* // or get().
* mozilla::ThreadLocal<int> tlsKey;
* if (!tlsKey.init()) {
* // deal with the error
* }
*
* // Set the TLS value
* tlsKey.set(123);
*
* // Get the TLS value
* int value = tlsKey.get();
*/
template<typename T>
class ThreadLocal
{
#if defined(XP_WIN)
typedef unsigned long key_t;
#else
typedef pthread_key_t key_t;
#endif
union Helper
{
void* mPtr;
T mValue;
};
public:
MOZ_WARN_UNUSED_RESULT inline bool init();
inline T get() const;
inline void set(const T aValue);
bool initialized() const { return mInited; }
private:
key_t mKey;
bool mInited;
};
template<typename T>
inline bool
ThreadLocal<T>::init()
{
Bug 895322 - Part 1: Replace the usages of MOZ_STATIC_ASSERT with C++11 static_assert; r=Waldo This patch was mostly generated by running the following scripts on the codebase, with some manual changes made afterwards: # static_assert.sh #!/bin/bash # Command to convert an NSPR integer type to the equivalent standard integer type function convert() { echo "Converting $1 to $2..." find . ! -wholename "*nsprpub*" \ ! -wholename "*security/nss*" \ ! -wholename "*/.hg*" \ ! -wholename "obj-ff-dbg*" \ ! -name nsXPCOMCID.h \ ! -name prtypes.h \ -type f \ \( -iname "*.cpp" \ -o -iname "*.h" \ -o -iname "*.cc" \ -o -iname "*.mm" \) | \ xargs -n 1 `dirname $0`/assert_replacer.py #sed -i -e "s/\b$1\b/$2/g" } convert MOZ_STATIC_ASSERT static_assert hg rev --no-backup mfbt/Assertions.h \ media/webrtc/signaling/src/sipcc/core/includes/ccapi.h \ modules/libmar/src/mar_private.h \ modules/libmar/src/mar.h # assert_replacer.py #!/usr/bin/python import sys import re pattern = re.compile(r"\bMOZ_STATIC_ASSERT\b") def replaceInPlace(fname): print fname f = open(fname, "rw+") lines = f.readlines() for i in range(0, len(lines)): while True: index = re.search(pattern, lines[i]) if index != None: index = index.start() lines[i] = lines[i][0:index] + "static_assert" + lines[i][index+len("MOZ_STATIC_ASSERT"):] for j in range(i + 1, len(lines)): if lines[j].find(" ", index) == index: lines[j] = lines[j][0:index] + lines[j][index+4:] else: break else: break f.seek(0, 0) f.truncate() f.write("".join(lines)) f.close() argc = len(sys.argv) for i in range(1, argc): replaceInPlace(sys.argv[i]) --HG-- extra : rebase_source : 4b4a4047d82f2c205b9fad8d56dfc3f1afc0b045
2013-07-18 17:59:53 +00:00
static_assert(sizeof(T) <= sizeof(void*),
"mozilla::ThreadLocal can't be used for types larger than "
"a pointer");
MOZ_ASSERT(!initialized());
#ifdef XP_WIN
mKey = TlsAlloc();
mInited = mKey != 0xFFFFFFFFUL; // TLS_OUT_OF_INDEXES
#else
mInited = !pthread_key_create(&mKey, nullptr);
#endif
return mInited;
}
template<typename T>
inline T
ThreadLocal<T>::get() const
{
MOZ_ASSERT(initialized());
Helper h;
#ifdef XP_WIN
h.mPtr = TlsGetValue(mKey);
#else
h.mPtr = pthread_getspecific(mKey);
#endif
return h.mValue;
}
template<typename T>
inline void
ThreadLocal<T>::set(const T aValue)
{
MOZ_ASSERT(initialized());
Helper h;
h.mValue = aValue;
#ifdef XP_WIN
bool succeeded = TlsSetValue(mKey, h.mPtr);
#else
bool succeeded = !pthread_setspecific(mKey, h.mPtr);
#endif
if (!succeeded) {
MOZ_CRASH();
}
}
} // namespace mozilla
#endif /* mozilla_ThreadLocal_h */