From effe03fd9602cb01734dfaa9f24a3c9c52320568 Mon Sep 17 00:00:00 2001 From: Akash Mozumdar Date: Thu, 4 Oct 2018 19:52:16 -0400 Subject: [PATCH] rearrange textthread logic. dont have threads where not needed. --- GUI/host/textthread.cc | 26 ++++++++++++++++---------- GUI/host/textthread.h | 10 ++++------ 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/GUI/host/textthread.cc b/GUI/host/textthread.cc index e48ca20..72e69ce 100644 --- a/GUI/host/textthread.cc +++ b/GUI/host/textthread.cc @@ -10,10 +10,9 @@ TextThread::TextThread(ThreadParam tp, DWORD status) : handle(ThreadCounter++), TextThread::~TextThread() { - SetEvent(deletionEvent); - flushThread.join(); - CloseHandle(deletionEvent); - LOCK(ttMutex); + SetEvent(cancelFlushEvent); + flusher.join(); + CloseHandle(cancelFlushEvent); } std::wstring TextThread::GetStore() @@ -27,10 +26,7 @@ void TextThread::Flush() std::wstring sentence; { LOCK(ttMutex); - if (buffer.size() < MaxBufferSize && (GetTickCount() - timestamp < FlushDelay || buffer.size() < 2)) return; - sentence = status & USING_UNICODE - ? std::wstring((wchar_t*)buffer.data(), buffer.size() / 2) - : StringToWideString(std::string(buffer.data(), buffer.size()), status & USING_UTF8 ? CP_UTF8 : SHIFT_JIS); + sentence = buffer; buffer.clear(); } AddSentence(sentence); @@ -46,9 +42,19 @@ void TextThread::AddSentence(std::wstring sentence) void TextThread::AddText(const BYTE* data, int len) { + if (buffer.size() > MaxBufferSize) Flush(); + SetEvent(cancelFlushEvent); + flusher.join(); + flusher = std::thread([&] + { + ResetEvent(cancelFlushEvent); + WaitForSingleObject(cancelFlushEvent, FlushDelay); + Flush(); + }); LOCK(ttMutex); - buffer.insert(buffer.end(), data, data + len); - timestamp = GetTickCount(); + buffer += status & USING_UNICODE + ? std::wstring((wchar_t*)data, len / 2) + : StringToWideString(std::string((char*)data, len), status & USING_UTF8 ? CP_UTF8 : SHIFT_JIS); } // EOF diff --git a/GUI/host/textthread.h b/GUI/host/textthread.h index cabb49f..bdd3d3e 100644 --- a/GUI/host/textthread.h +++ b/GUI/host/textthread.h @@ -10,6 +10,7 @@ class TextThread { typedef std::function ThreadOutputCallback; + public: TextThread(ThreadParam tp, DWORD status); ~TextThread(); @@ -17,7 +18,6 @@ public: std::wstring GetStore(); void AddText(const BYTE* data, int len); void AddSentence(std::wstring sentence); - void RegisterOutputCallBack(ThreadOutputCallback cb) { Output = cb; } const int64_t handle; @@ -31,13 +31,11 @@ public: private: void Flush(); - std::vector buffer; + std::wstring buffer; std::wstring storage; std::recursive_mutex ttMutex; - - HANDLE deletionEvent = CreateEventW(nullptr, FALSE, FALSE, NULL); - std::thread flushThread = std::thread([&] { while (WaitForSingleObject(deletionEvent, 10) == WAIT_TIMEOUT) Flush(); }); - DWORD timestamp = GetTickCount(); + std::thread flusher = std::thread([] {}); + HANDLE cancelFlushEvent = CreateEventW(nullptr, TRUE, TRUE, NULL); ThreadOutputCallback Output; DWORD status;