I'm currently building an app browser-like. One part is the UI the other is an access to the Android device
I have a class DeviceMngr which is used to instantiate different methods to access to an android device. The instantiate class is gave as argument to the QMainWindow. The QMainWindow will display a QTreewidget and get data from the android device using the MyMtpDevice.
DeviceMngr *MyMtpDevice = new DeviceMngr;
error = MyMtpDevice->OpenDevice();
MainUI MyWindow(*MyMtpDevice);
How to create a thread in which all call to DeviceMngr such as OpenDevice is done in a separate thread and any other call to a method of this class.
I want a thread for the UI and a thread for the DeviceMngr
Any idea of implementation ? I have try some but seems not working
It depends on exactly what you need. You can do several things, and one of the solutions you should look at is boost::thread
and boost::io_service
. It works by creating a thread (in your DeviceMngr
class) and posting work to it (from other threads):
class DeviceMngr
{
public:
DeviceMngr();
~DeviceMngr();
void OpenDevice();
private:
void DeviceMngrThread();
void _OpenDevice() {}
boost::asio::io_service io_service;
boost::thread thread;
bool run;
};
DeviceMngr::DeviceMngr()
: io_service(),
thread(&DeviceMngr::DeviceMngrThread, this), // create thread
run(true) // start running thread
{
}
DeviceMngr::~DeviceMngr()
{
run = false; // stop running the thread
thread.join(); // wait for the thread to finish
io_service.stop();
}
void DeviceMngr::DeviceMngrThread()
{
while (run)
{
// Process work
io_service.run();
// Prepare for more work
io_service.reset();
}
}
void DeviceMngr::OpenDevice()
{
// Post work to do
io_service.post(boost::bind(&DeviceMngr::_OpenDevice, this));
}
Calling OpenDevice
will simply post work for the DeviceMngr
thread to handle. This simple example should help you get started and to learn how threads work. I would suggest starting with small examples so you can learn how it all works together (seeing as though calls to OpenDevice
will not be synchronous. If you require synchronisation, you may need to look towards boost synchronisation