ThreadLocal

来源:互联网 发布:北京 云计算 大会 编辑:程序博客网 时间:2024/04/28 18:17

// Helper functions that abstract the cross-platform APIs.  Do not use directly.

struct ThreadLocalPlatform {

#if defined(OS_WIN)

  typedef int SlotType;

#elif defined(OS_POSIX)

  typedef pthread_key_t SlotType;

#endif

 

  static void AllocateSlot(SlotType& slot);

  static void FreeSlot(SlotType& slot);

  static void* GetValueFromSlot(SlotType& slot);

  static void SetValueInSlot(SlotType& slot, void* value);

};

 

template <typename Type>

class ThreadLocalPointer {

 public:

  ThreadLocalPointer() : slot_() {

    ThreadLocalPlatform::AllocateSlot(slot_);

  }

 

  ~ThreadLocalPointer() {

    ThreadLocalPlatform::FreeSlot(slot_);

  }

 

  Type* Get() {

    return static_cast<Type*>(ThreadLocalPlatform::GetValueFromSlot(slot_));

  }

 

  void Set(Type* ptr) {

    ThreadLocalPlatform::SetValueInSlot(slot_, ptr);

  }

 

 private:

  typedef ThreadLocalPlatform::SlotType SlotType;

 

  SlotType slot_;

 

  DISALLOW_COPY_AND_ASSIGN(ThreadLocalPointer<Type>);

};

 

class ThreadLocalBoolean {

 public:

  ThreadLocalBoolean() { }

  ~ThreadLocalBoolean() { }

 

  bool Get() {

    return tlp_.Get() != NULL;

  }

 

  void Set(bool val) {

    tlp_.Set(reinterpret_cast<void*>(val ? 1 : 0));

  }

 

 private:

  ThreadLocalPointer<void> tlp_;

 

  DISALLOW_COPY_AND_ASSIGN(ThreadLocalBoolean);

};

void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
  slot = TlsAlloc();
  CHECK(slot != TLS_OUT_OF_INDEXES);
}
// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
  if (!TlsFree(slot)) {
    NOTREACHED() << "Failed to deallocate tls slot with TlsFree().";
  }
}
// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
  return TlsGetValue(slot);
}
// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
  if (!TlsSetValue(slot, value)) {
    CHECK(false) << "Failed to TlsSetValue().";
  }
}

原创粉丝点击