BBS2chProxyThreadInfo.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #pragma once
  2. #include <map>
  3. #include <string>
  4. #if (defined(__clang__) && defined(_LIBCPP_VERSION)) || (__cplusplus >= 201103L)
  5. #include <memory>
  6. #else
  7. #include <tr1/memory>
  8. #endif
  9. #include <pthread.h>
  10. struct BBS2chProxyThreadInfo
  11. {
  12. int lastResNum;
  13. int cachedSize;
  14. std::string cachedData;
  15. BBS2chProxyThreadInfo() : lastResNum(0), cachedSize(0) {};
  16. ~BBS2chProxyThreadInfo() {};
  17. };
  18. struct BBS2chThreadIdentifier {
  19. std::string hostPrefix;
  20. std::string host;
  21. std::string board;
  22. std::string key;
  23. };
  24. #if (defined(__clang__) && defined(_LIBCPP_VERSION)) || (__cplusplus >= 201103L)
  25. typedef std::shared_ptr<BBS2chProxyThreadInfo> PBBS2chProxyThreadInfo;
  26. #else
  27. typedef std::tr1::shared_ptr<BBS2chProxyThreadInfo> PBBS2chProxyThreadInfo;
  28. #endif
  29. class BBS2chProxyThreadCache
  30. {
  31. private:
  32. pthread_mutex_t _mutex;
  33. std::map<std::string, PBBS2chProxyThreadInfo> _cache;
  34. public:
  35. BBS2chProxyThreadCache() {
  36. pthread_mutex_init(&_mutex, NULL);
  37. }
  38. ~BBS2chProxyThreadCache() {
  39. pthread_mutex_destroy(&_mutex);
  40. }
  41. void set(const std::string &key, PBBS2chProxyThreadInfo info) {
  42. pthread_mutex_lock(&_mutex);
  43. _cache.insert(std::make_pair(key, info));
  44. pthread_mutex_unlock(&_mutex);
  45. }
  46. PBBS2chProxyThreadInfo get(const std::string &key) {
  47. PBBS2chProxyThreadInfo info;
  48. pthread_mutex_lock(&_mutex);
  49. std::map<std::string, PBBS2chProxyThreadInfo>::iterator it = _cache.find(key);
  50. if(it != _cache.end()) {
  51. info = it->second;
  52. }
  53. pthread_mutex_unlock(&_mutex);
  54. return info;
  55. }
  56. PBBS2chProxyThreadInfo pop(const std::string &key) {
  57. PBBS2chProxyThreadInfo info;
  58. pthread_mutex_lock(&_mutex);
  59. std::map<std::string, PBBS2chProxyThreadInfo>::iterator it = _cache.find(key);
  60. if(it != _cache.end()) {
  61. info = it->second;
  62. _cache.erase(it);
  63. }
  64. pthread_mutex_unlock(&_mutex);
  65. return info;
  66. }
  67. void remove(const std::string &key) {
  68. pthread_mutex_lock(&_mutex);
  69. std::map<std::string, PBBS2chProxyThreadInfo>::iterator it = _cache.find(key);
  70. if(it != _cache.end()) {
  71. _cache.erase(it);
  72. }
  73. pthread_mutex_unlock(&_mutex);
  74. }
  75. };