multithreading - C++/MFC/ATL Thread-Safe String read/write -
i have mfc class threads launched , threads need modify cstring members of main class.
i hate mutex locks, there must easier way this.
i thinking use boost.org library or atl::atomic or shared_ptr variables.
what best method of reading , writting string , thread safe?
class myclass { public: void myclass(); static uint mythread(lpvoid parg); cstring m_strinfo; }; void myclass::myclass() { afxbeginthread(mythread, this); cstring strtmp=m_strinfo; // may cause crash } uint myclass::mythread(lpvoid parg) { myclass pclass=(myclass*)pard; pclass->m_strinfo=_t("new value"); // non thread-safe change }
according msdn shared_ptr works automatically https://msdn.microsoft.com/en-us/library/bb982026.aspx
so better method?
#include <memory> class myclass { public: void myclass(); static uint mythread(lpvoid parg); std::shared_ptr<cstring> m_strinfo; // ******** }; void myclass::myclass() { afxbeginthread(mythread, this); cstring strtmp=m_strinfo; // may cause crash } uint myclass::mythread(lpvoid parg) { myclass pclass=(myclass*)pard; shared_ptr<cstring> newvalue(new cstring()); newvalue->setstring(_t("new value")); pclass->m_strinfo=newvalue; // thread-safe change? }
you implement kind of lockless way achieve that, depends on how use myclass , thread. if thread processing data , after processing it, need update myclass, consider putting string data in other class ex.:
struct stringdata { cstring m_strinfo; };
then inside myclass:
class myclass { public: void myclass(); static uint mythread(lpvoid parg); stringdata* m_pstrdata; stringdata* m_pstrdataforthreads; };
now, idea in ie. main thread code use m_pstrdata, need use atomics store local pointer ie.:
void myclass::myclass() { afxbeginthread(mythread, this); stringdata* m_pstrdatatemp = atomic_read(m_pstrdata); if ( m_pstrdatatemp ) cstring strtmp=m_pstrdatatemp->m_strinfo; // may not cause crash }
once thread finished processing data, , wants update string, atomically assign m_pstrdataforthreads
m_pstrdata
, , allocate new m_pstrdataforthreads
,
the problem how safely delete m_pstrdata, suppose use here std::shared_ptr.
in end looks kind of complicated , imo not worth effort, @ least hard tell if thread safe, , when code more complicated - still thread safe. single worker thread case, , have multiple threads. thats why critical section starting point, , if slow think of using lockless approach.
btw. depending on how string data updated think using postmessage
safely pass pointer new string, main thread.
[edit]
atomic_macro not exists, place holder make compile use ie. c++11 atomics, example below:
#include <atomic> ... std::atomic<uint64_t> sharedvalue(0); sharedvalue.store(123, std::memory_order_relaxed); // atomically store uint64_t ret = sharedvalue.load(std::memory_order_relaxed); // atomically read std::cout << ret;
Comments
Post a Comment