[Interest] Executing a small function as a thread

André Somers andre at familiesomers.nl
Tue Mar 17 16:21:58 CET 2015


Sze Howe Koh schreef op 17-3-2015 om 16:15:
> Hi,
>
> On 17 March 2015 at 23:06, Syam Krishnan <syamcr at gmail.com> wrote:
>> On 03/17/2015 08:03 PM, André Somers wrote:
>>> Might I suggest a third method? Use QtConcurrent::run(yourFunction)
>>> instead.
>> The documentation on QtConcurrent::run() says
>> "Note that the function may not run immediately; the function will only
>> be run when a thread is available."
> These threads are part of the global thread pool. The documentation
> means, *if you are currently using all available threads in the pool*,
> then QtConcurrent::run() will wait until one of those threads finish
> before running. However, since you only want one instance running at a
> time, then it's not a problem -- your function will run immediately.
Well, in any multi-threaded programming, you basicaly have no control 
over when something runs. That's up to the OS, not you. It will usually 
be "soonish", but...
>> That is not acceptable to me. I am looking for the simplest solution
>> that has the least overhead.
> QtConcurrent::run() is the simplest solution available.
>
> QtConcurrent uses QThreadPool internally. One of the reasons
> QThreadPool was created was to reduce the overhead of starting new
> threads.
Indeed. And that makes it quite a light solution.
>
>> And I should have mentioned that only one instance of do_something()
>> must be executing at any time.
>> I am using QAtomicInt to control calls to this function. So when a
>> second event is raised, it will check if
>> the thread is already executing. If it is, it will wait till the thread
>> execution is complete.
> Yes, that is compatible with QtConcurrent::run().
In fact, it is easier. Simply check the state of the future. No need for 
a QAtomicInt who's value is not self-evident. No need to really wait for 
the value/state to change either: you can attach a QFutureWatcher and 
get a notification when the future is finished. That way, you don't 
waste cycles bussy-waiting for another thread.

André




More information about the Interest mailing list