more efficient thread safe wrapper

This commit is contained in:
Akash Mozumdar 2018-12-21 14:11:40 -05:00
parent 4ea5c9cb32
commit afea96e9d5
3 changed files with 10 additions and 10 deletions

View File

@ -53,8 +53,8 @@ namespace
WinMutex viewMutex; WinMutex viewMutex;
}; };
ThreadSafePtr<std::unordered_map<ThreadParam, std::shared_ptr<TextThread>>> textThreadsByParams; ThreadSafe<std::unordered_map<ThreadParam, std::shared_ptr<TextThread>>> textThreadsByParams;
ThreadSafePtr<std::unordered_map<DWORD, ProcessRecord>> processRecordsByIds; ThreadSafe<std::unordered_map<DWORD, ProcessRecord>> processRecordsByIds;
ThreadParam CONSOLE{ 0, -1ULL, -1ULL, -1ULL }, CLIPBOARD{ 0, 0, -1ULL, -1ULL }; ThreadParam CONSOLE{ 0, -1ULL, -1ULL, -1ULL }, CLIPBOARD{ 0, 0, -1ULL, -1ULL };

View File

@ -22,7 +22,7 @@ public:
void AddSentence(std::wstring sentence); void AddSentence(std::wstring sentence);
void Push(const BYTE* data, int len); void Push(const BYTE* data, int len);
const ThreadSafePtr<std::wstring> storage; ThreadSafe<std::wstring> storage;
const int64_t handle; const int64_t handle;
const std::wstring name; const std::wstring name;
const ThreadParam tp; const ThreadParam tp;

View File

@ -5,25 +5,25 @@
template <typename T> using Array = T[]; template <typename T> using Array = T[];
template<typename E, typename M = std::mutex, template<typename...> typename P = std::unique_ptr> template<typename E, typename M = std::mutex>
class ThreadSafePtr class ThreadSafe
{ {
public: public:
template <typename ...Args> ThreadSafePtr(Args ...args) : ptr(new E(args...)), mtxPtr(new M) {} template <typename ...Args> ThreadSafe(Args ...args) : contents(args...) {}
auto operator->() const auto operator->()
{ {
struct struct
{ {
E* operator->() { return ptr; } E* operator->() { return ptr; }
std::unique_lock<M> lock; std::unique_lock<M> lock;
E* ptr; E* ptr;
} lockedProxy{ std::unique_lock<M>(*mtxPtr), ptr.get() }; } lockedProxy{ std::unique_lock(mtx), &contents };
return lockedProxy; return lockedProxy;
} }
private: private:
P<E> ptr; E contents;
P<M> mtxPtr; M mtx;
}; };
struct DefHandleCloser { void operator()(void* h) { CloseHandle(h); } }; struct DefHandleCloser { void operator()(void* h) { CloseHandle(h); } };