Is possible call method in background thread in same class? Using C++/QT without c++11.
Or repeatedly everly 5 seconds run foo2.
Example
class MyClass
{
public:
void foo(...)
{
// in another thread run foo2
foo2;
}
.
.
.
protected:
void foo2(...){}
}
thanks
to run some function in a separate thread you can use QtConcurrent::run (i use it with QFutureWatcher). To run it every 5 or so seconds, use QElapsedTimer class
QFuture<void> future = QtConcurrent::run(this, &MyClass::foo2, ...foo2 arguments);
http://qt-project.org/doc/qt-4.8/qtconcurrentrun.html#run or check it here https://stackoverflow.com/search?q=QtConcurrent%3A%3Arun
or you can subclass QThread, reimplement run() with the stuff you want to happen in your thread, and then create an instance of your thread and call start() on it.
Related
I try to start QTimer from another thread ( to get better accuracy ).
I think that problem is with function connect but let see my code:
//code from constructor of parent.cpp class
{
//run_clock_timer(this); // this works
std::thread t1{ [this] { run_clock_timer(this); } }; //not works
t1.join();
}
And function:
void class::run_clock_timer(class* inst){
QTimer * test = new QTimer(inst);
connect(test, SIGNAL(timeout()), inst, SLOT(updateTime()));
test->setInterval(50);
test->start(timer_precision);
}
Debugger told me that code from run_clock_timer was run, but no result.
I think i will do it with no problem when i use QThread, but i want to use std::thread.
So whats wrong with my function ?
The problem is that QTimer depends on the ability to interact with a running Qt event loop in order to perform its task. Since a non-Qt thread has no event loop, the QTimer can't do its job. (i.e. there has to be some Qt code running in the thread, that will emit the timeout() signal, that doesn't just happen on its own)
I have a application that hast many threads.I want to exit the threads when I close my main application and call thread destructors to make necesseary clean up.
Class Thread :public QThread{
Thread();
run(){
while(1){
//do work
}
}
~Thread(){
//want to make clean up
}
};
Class my_app :public QCoreapplication{
my_app(){
Thread th1;
connect(&th1,SIGNAL(finished()),&th1,deleteLater());
connect(&th1,SIGNAL(finished()),&th1,quit());
}
};
//And my th1 thread runs in while.So I know that is the problem it runs on while and never emits the finished signal
//How can be achievable?
Do not subclass QThread
in worker loop provide some thread safe flag which will indicate that worker should end its job.
Before terminate application you should call QThread::wait to ensure that thread will end gracefully before application is terminated.
In your run function the while loop will cause your thread to never stop unless you manage thread termination by your self like:
Class Thread :public QThread{
Thread();
protected:
void run()
{
while(1)
{
if(this->finishThread==true)
return;
}
}
private:
bool finishThread;
}
You are better to derive your class from QObject and use moveToThread. You can do this in the constructor of your class:
th = new QThread();
this->setParent(0);
this->moveToThread(th);
clientSocket.moveToThread(th);
QObject::connect(th,SIGNAL(started()),this,SLOT(OnStarted()));
QObject::connect(th,SIGNAL(finished()),this,SLOT(OnFinished()));
th->start();
Your initialization and termination tasks should be done in OnStarted() and OnFinished() slots respectively.
In the destructor of your class add this:
th->quit();
th->wait();
In my multi-threaded programs I often use an approach like shown below to synchronize access to data:
class MyAsyncClass
{
public: // public thread safe interface of MyAsyncClass
void start()
{
// add work to io_service
_ioServiceWork.reset(new boost::asio::io_service::work(_ioService));
// start io service
_ioServiceThread = boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(&boost::asio::io_service::run, &_ioService)));
}
void stop()
{
_ioService.post(boost::bind(&MyAsyncClass::stop_internal, this));
// QUESTION:
// how do I wait for stop_internal to finish here?
// remove work
_ioServiceWork.reset();
// wait for the io_service to return from run()
if (_ioServiceThread && _ioServiceThread->joinable())
_ioServiceThread->join();
// allow subsequent calls to run()
_ioService.reset();
// delete thread
_ioServiceThread.reset();
}
void doSometing()
{
_ioService.post(boost::bind(&MyAsyncClass::doSometing_internal, this));
}
private: // internal handlers
void stop_internal()
{
_myMember = 0;
}
void doSomething_internal()
{
_myMember++;
}
private: // private variables
// io service and its thread
boost::asio::io_service _ioService;
boost::shared_ptr<boost::thread> _ioServiceThread;
// work object to prevent io service from running out of work
std::unique_ptr<boost::asio::io_service::work> _ioServiceWork;
// some member that should be modified only from _ioServiceThread
int _myMember;
};
The public interface of this class is thread-safe in the sense that its public methods can be called from any thread and boost::asio::io_service takes care that access to the private members of this class are synchronized. Therefore the public doSomething() does nothing but posting the actual work into the io_service.
The start() and stop() methods of MyAsyncClass obviously start and stop processing in MyAsyncClass. I want to be able to call MyAsyncClass::stop() from any thread and it should not return before the uninitialization of MyAsyncClass has finished.
Since in this particular case I need to modify one of my private members (that needs synchronized access) when stopping, I introduced a stop_internal() method which I post to the io_service from stop().
Now the question is: How can I wait for the execution of stop_internal() to finish inside stop()? Note that I cannot call stop_internal() directly because it would run in the wrong thread.
Edit:
It would be nice to have a solution that also works if MyAsyncClass::stop() is called from the _ioServiceThread, so that MyAsyncClass can also stop itself.
I just found a very nice solution myself:
Instead of removing work (resetting _ioServiceWork) in stop(), I do it at the end of stop_internal(). This means that _ioServiceThread->join() blocks until stop_internal() has finished - exactly what I want.
The nice thing about this solution is that it doesn't need any mutex or condition variable or stuff like this.
I am trying to create this function in order to exec another function after X time:
void execAfter(double time, void *(*func)(void *), t_params *params);
I have made an Thread encapsulation and a Time encapsulation (objects Thread and Time).
What I want to do in pseudo code:
Call execAfter
instantiate Thread
call thread->create(*funcToExec, *params, timeToWait)
[inside thread, leaving execAfter]
instanciate Time object
wait for X time
exec funcToExec
delete Time object
[leaving thread, back to execAfter]
delete Thread object <---- probleme is here, see description below.
return ;
How can I delete my Thread object properly, without blocking the rest of the execution nor taking the risk to delete it before required time has elapsed.
I am quite lost, any help appreciated!
Using std::thread and lambdas, you could do it something like this:
void execAfter(const int millisecs, std::function<void(void*)> func, void* param)
{
std::thread thread([=](){
std::this_thread::sleep_for(std::chrono::milliseconds(millisecs));
func(param);
});
// Make the new thread "detached" from the parent thread
thread.detach();
}
The "magic" that you are looking for is the detach call.
I learn from the following links that sub classing a QThread is not a correct way of using it...the proper way is to subclass the QObject and then move the object of QObject class to the respective thread using moveToThread() function...i followed the following links..
link 1 and link 2...but my question is then how will i be able to use msleep() and usleep() protected static functions ? or will i use QTimer to make a thread wait for some time ?
No need for timers. For waiting, Qt provides QWaitCondition. You can implement something like this:
#include <QWaitCondition>
#include <QMutex>
void threadSleep(unsigned long ms)
{
QMutex mutex;
mutex.lock();
QWaitCondition waitCond;
waitCond.wait(&mutex, ms);
mutex.unlock();
}
This is a normal function. You can of course implement it as a member function too, if you want (it can be a static member in that case.)
One solution would be to create a timer:
class Worker: public QObject
{
///...
private slots:
void doWork()
{
//...
QTimer::singleShot(delay, this, SLOT(continueDoingWork()));
}
void continueDoingWork()
{
}
};
Sometimes, you only need to run an operation in a different thread and all this event loops and threads are overhead. Then you can use QtConcurent framework:
class Worker
{
public:
void doWork()
{
//...
}
} worker;
//...
QtConcurent::run(worker, &Worker::doWork);
Then, I usually use mutexes to simulate the sleep operations:
QMutex m;
m.lock();
m.tryLock(delay);
The canonical answer is "use signals and slots."
For example, if you want a QObject in a thread to "wake itself up" after a certain period of time, consider QTimer::singleShot(), passing in the slot as the third argument. This can be called from the slot in question, resulting in periodic execution.
You can't let a different thread sleep without cooperation of this thread, thats the reason the member functions of QThread are protected. If you want to sleep a different thread you need to use a condition variable or a timer inside
If you want so sleep the current thread with usleep(), the simplest way is to subclass it - its perfectly fine as long as you don't need QThreadPool, a thread local event loop or similar.