| OLD | NEW |
| 1 // Copyright 2013 The Chromium Authors. All rights reserved. | 1 // Copyright 2013 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 #include "mojo/public/utility/thread_local.h" | 5 #ifndef MOJO_PUBLIC_UTILITY_LIB_THREAD_LOCAL_H_ |
| 6 #define MOJO_PUBLIC_UTILITY_LIB_THREAD_LOCAL_H_ |
| 6 | 7 |
| 7 #include <assert.h> | 8 #ifndef _WIN32 |
| 8 #include <pthread.h> | 9 #include <pthread.h> |
| 10 #endif |
| 11 |
| 12 #include "mojo/public/system/macros.h" |
| 9 | 13 |
| 10 namespace mojo { | 14 namespace mojo { |
| 11 namespace internal { | 15 namespace internal { |
| 12 | 16 |
| 13 // static | 17 // Helper functions that abstract the cross-platform APIs. |
| 14 void ThreadLocalPlatform::AllocateSlot(SlotType* slot) { | 18 struct ThreadLocalPlatform { |
| 15 if (pthread_key_create(slot, NULL) != 0) { | 19 #ifdef _WIN32 |
| 16 assert(false); | 20 typedef unsigned long SlotType; |
| 21 #else |
| 22 typedef pthread_key_t SlotType; |
| 23 #endif |
| 24 |
| 25 static void AllocateSlot(SlotType* slot); |
| 26 static void FreeSlot(SlotType slot); |
| 27 static void* GetValueFromSlot(SlotType slot); |
| 28 static void SetValueInSlot(SlotType slot, void* value); |
| 29 }; |
| 30 |
| 31 // This class is intended to be statically allocated. |
| 32 template <typename P> |
| 33 class ThreadLocalPointer { |
| 34 public: |
| 35 ThreadLocalPointer() : slot_() { |
| 17 } | 36 } |
| 18 } | |
| 19 | 37 |
| 20 // static | 38 void Allocate() { |
| 21 void ThreadLocalPlatform::FreeSlot(SlotType slot) { | 39 ThreadLocalPlatform::AllocateSlot(&slot_); |
| 22 if (pthread_key_delete(slot) != 0) { | |
| 23 assert(false); | |
| 24 } | 40 } |
| 25 } | |
| 26 | 41 |
| 27 // static | 42 void Free() { |
| 28 void* ThreadLocalPlatform::GetValueFromSlot(SlotType slot) { | 43 ThreadLocalPlatform::FreeSlot(slot_); |
| 29 return pthread_getspecific(slot); | 44 } |
| 30 } | |
| 31 | 45 |
| 32 // static | 46 P* Get() { |
| 33 void ThreadLocalPlatform::SetValueInSlot(SlotType slot, void* value) { | 47 return static_cast<P*>(ThreadLocalPlatform::GetValueFromSlot(slot_)); |
| 34 if (pthread_setspecific(slot, value) != 0) { | |
| 35 assert(false); | |
| 36 } | 48 } |
| 37 } | 49 |
| 50 void Set(P* value) { |
| 51 ThreadLocalPlatform::SetValueInSlot(slot_, value); |
| 52 } |
| 53 |
| 54 private: |
| 55 ThreadLocalPlatform::SlotType slot_; |
| 56 }; |
| 38 | 57 |
| 39 } // namespace internal | 58 } // namespace internal |
| 40 } // namespace mojo | 59 } // namespace mojo |
| 60 |
| 61 #endif // MOJO_PUBLIC_UTILITY_LIB_THREAD_LOCAL_H_ |
| OLD | NEW |