PDA

View Full Version : How to start a thread (inline)



DiamonDogX
28th May 2009, 21:27
I am aware that to execute something in a separate thread, one can simply extend QThread, implement run(), and write the pertinent code in the run method. But is there a way to execute an arbitrary block of code in a separate thread w/o having to create a whole new class? For example, maybe when I click a button I want a task to be executed in a separate thread, etc. Thanks.

lni
28th May 2009, 21:41
I am aware that to execute something in a separate thread, one can simply extend QThread, implement run(), and write the pertinent code in the run method. But is there a way to execute an arbitrary block of code in a separate thread w/o having to create a whole new class? For example, maybe when I click a button I want a task to be executed in a separate thread, etc. Thanks.

Use OpenMP



#pragma omp parallel default(none) shared(n,a,b,c,d) private(i)
{
#pragma omp for nowait
for (i=0; i<n-1; i++) b[i] = (a[i] + a[i+1])/2;

#pragma omp for nowait
for ( i=0; i<n; i++ ) d[i] = 1./c[i];

} /* -- End of parallel region -- */



Or google search for QtConcurrent

wysota
28th May 2009, 21:57
See QRunnable and QThreadPool or better yet QtConcurrent::run.

DiamonDogX
28th May 2009, 22:38
While we're on the subject, if I am executing code in another thread (i.e. a thread that is not the UI thread), is there a way to manually execute a piece of code on the UI thread?

wysota
28th May 2009, 22:53
Yes. Either post an event to the main thread and catch it from within QObject::customEvent() of the object living in the main thread or use QMetaObject::invokeMethod() with Qt::QueuedConnection as the last parameter. The method you call has to be a slot.