Sharing information between threads using mutex vs messages
Edit : My question is still unanswered if anyone would like to take a shot at it
In my MFC C++ application, I share information between GUI thread and worker thread as shown in the following code. I have created a struct called inParams, which needs to be referenced from within both the main thread and the worker thread. Hence, I declare its members of std::atomic type, and in cases where atomic types dont exists, eg. for floats, I use a dedicated mutex. The Main Thread does operation Foo with this information and the worker thread does operation Bar. Foo and Bar run concurrently, and both can see changes to param1 and param2 as they are updated by user.
struct inParams{
std::atomic_int param1;
std::atomic_size_t param2;
std::vector<customType> giantData;
std::mutex giantDataMutex;
};
void myController::DoMainTask(){
// Keep Handling GUI Events in this thread (main thread)
// Create a Worker thread to do another task, I'll call it Bar
SpawnWorkerThread()
}
void myController::SpawnWorkerThread(){
std::thread t(&myController::tfunc, this);
t.detach();
}
void myController::OnTimer(){ // say every 50 ms, just to simulate concurrency
// When user changes param1 or param2, the changes affect here also
Foo(inParams.param1, inParams.param2/* .. params list .. */);
}
void myController::tfunc(){
while(1){
// When user changes param1 or param2, the changes affect here also
Bar(inParams.param1, inParams.param2, /* .. params list .. */); //
}
}
void myController::OnEventParam1(){ // User changed param1 in GUI
inParams.param1 = GetValue( param1EditBox ); // GetValue gets value from Edit Box
}
void myController::OnEventParams2(){ // User changed param2 in GUI
inParams.param2 = GetValue( param2EditBox );
}
My question is this - Is this an AntiPattern? Should I be using messages instead to share this information as opposed to sharing the params using mutex (by making them atomic)?
Do C++11 std::threads allow messaging or should I rely on PostThreadMessage API from WinAPI?
You are using polling/timer to poll the shared variables. The advantage of using messages (PostMessage and PostThreadMessage) is it eliminates polling and lets the threads be event-driven. It doesn't matter whether you pass data in the message or use the synchronized access that you have. Either way is fine, but polling is bad.
链接地址: http://www.djcxy.com/p/78220.html上一篇: 使用std :: atomic的无模互斥模的安全增量
下一篇: 使用互斥锁与消息在线程之间共享信息