问题
Problem statement : to track an object with a camera and move the camera in azimuth and elevation accordingly.
Process : camera acquires images of the object....each frame of camera is processed to find the object(which is supposed to be tracked...) and the information generated in each frame is passed to the mechanical device (gimbal...) to move the camera in pan and tilt...
Design : the main Gui is run in a thread and camera and gimbal in 2 other thread...info generated in camera thread is passed on to gimbal thread and the same thread(camera thread...) displays the tracked image...
CONSTRAINT: display rate is faster than move rate of gimbal...so in each frame...
- frame is processed and displayed (at 10 ms rate)
- info generated is passed onto gimbal
- gimbal thread is suspended for a longer time (100 ms) to give time to the mechanical parts to move and ensure no new update comes to gimbal till it completes its movement..
the following diagram shows the design of classes and signal and slot connections in Qt..
please suggest any better way to go about the problem if possible...
ERROR: sometimes i get an error...
QObject::killTimers: timers cannot be stopped from another thread
回答1:
To me you should just avoid to call functions like that between the thread, here is an idea, that is the way i would do to exchange safely a lot of data.
and you should have state machine with both thread accessing to a shared lockable variable (a pointer to use for your main thread that points to the ping or the pong buffer + a mutex for your lock)
this way you can change the way you use data, the "display" should use always the same pointer. It should acquire the lock when starting to read and releasing after.
The camera should write in the other buffer After the camera writed, the camera thread should try lo acquire the lock for the mutex and IF it acquires it (ie the other thread is not reading the other bufer), then the camera thread should take the lock and change the buffer pointed by the pointer used by the main thread)
This way you have no communication between threads just the mutual exclusion.
The biggest risk is to never being able to acquire the lock from the camera thread, here is a solution -> In order to limit the lock time, I advise you to have a second buffer in each thread so the lock time would be reduced to the "memcpy" duration. Add a bool to the structure, thats says if your camera updated the data or not.
If yes, the main thread copy the data. (and the camera can't swap pointers during this time) but once it is done, you main thread also reset the bool to false. And until this bool is back to true you don't need to lock to copy data. (now this is lock free exchange) Note that this is true only because reading the bool is an atomic action.
I hope it helps
(sorry for my english)
来源:https://stackoverflow.com/questions/12627084/class-design-in-qt-for-inter-thread-communication