- Main Page
- Namespaces
- Classes
- Files

# trdlocal.cpp

    00001 // trdlocal.cpp - written and placed in the public domain by Wei Dai
    00002
    00003 #include "pch.h"
    00004
    00005 #ifndef CRYPTOPP_IMPORTS
    00006 #ifdef THREADS_AVAILABLE
    00007
    00008 #include "trdlocal.h"
    00009
    00010 #ifdef HAS_WINTHREADS
    00011 #include <windows.h>
    00012 #endif
    00013
    00014 NAMESPACE_BEGIN(CryptoPP)
    00015
    00016 ThreadLocalStorage::Err::Err(const std::string& operation, int error)
    00017         : OS_Error(OTHER_ERROR, "ThreadLocalStorage: " + operation + " operation failed with error 0x" + IntToString(error, 16), operation, error)
    00018 {
    00019 }
    00020
    00021 ThreadLocalStorage::ThreadLocalStorage()
    00022 {
    00023 #ifdef HAS_WINTHREADS
    00024         m_index = TlsAlloc();
    00025         if (m_index == TLS_OUT_OF_INDEXES)
    00026                 throw Err("TlsAlloc", GetLastError());
    00027 #else
    00028         int error = pthread_key_create(&m_index, NULL);
    00029         if (error)
    00030                 throw Err("pthread_key_create", error);
    00031 #endif
    00032 }
    00033
    00034 ThreadLocalStorage::~ThreadLocalStorage()
    00035 {
    00036 #ifdef HAS_WINTHREADS
    00037         if (!TlsFree(m_index))
    00038                 throw Err("TlsFree", GetLastError());
    00039 #else
    00040         int error = pthread_key_delete(m_index);
    00041         if (error)
    00042                 throw Err("pthread_key_delete", error);
    00043 #endif
    00044 }
    00045
    00046 void ThreadLocalStorage::SetValue(void *value)
    00047 {
    00048 #ifdef HAS_WINTHREADS
    00049         if (!TlsSetValue(m_index, value))
    00050                 throw Err("TlsSetValue", GetLastError());
    00051 #else
    00052         int error = pthread_setspecific(m_index, value);
    00053         if (error)
    00054                 throw Err("pthread_key_getspecific", error);
    00055 #endif
    00056 }
    00057
    00058 void *ThreadLocalStorage::GetValue() const
    00059 {
    00060 #ifdef HAS_WINTHREADS
    00061         void *result = TlsGetValue(m_index);
    00062         if (!result && GetLastError() != NO_ERROR)
    00063                 throw Err("TlsGetValue", GetLastError());
    00064 #else
    00065         void *result = pthread_getspecific(m_index);
    00066 #endif
    00067         return result;
    00068 }
    00069
    00070 NAMESPACE_END
    00071
    00072 #endif  // #ifdef THREADS_AVAILABLE
    00073 #endif