<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm?]]></title><description><![CDATA[<p dir="auto">I feel like testing my new laptop's speed/core threading... :)</p>
<p dir="auto">My test will be calculating whether an input number is prime or not.  The size of the number will be "large", so Eratosthenes Sieve would cost too much space.  Instead I will run trial division.  So the initial, single-threaded algorithm will be:</p>
<pre><code>long dividend = ...;  // the number to test for primality
long limit = sqrt(test);
for (long divisor = 2; divisor &lt;= limit; divisor++)
    if (dividend % divisor == 0)
        return false;
return  true;
</code></pre>
<p dir="auto">Now the question is to how to split the task "optimally" for concurrent execution across available threads/cores.</p>
<p dir="auto">If I naively just set this off with some <strong>QtConcurrent</strong> method and a function/lambda which just returns the <code>dividend % divisor == 0</code> result for each number in range <code>2..limit</code> I <em>presume</em> there will be some overhead for initiating/terminating each thread which has only done a simple dividing and that will be far from optimal.  Right?</p>
<p dir="auto">If I were to do this myself with threads/cores I would go for something like:</p>
<pre><code>int threads = available_threads();  // maybe 8?
for (int thread = 0; thread &lt; threads; thread++)
{
    threadObj = createThread();
    threadObj-&gt;run(threadFunc, 2 + thread, limit, threads);
}
if (any_thread_returns_false())
    return false;
return true;

bool threadFunc(long start, long limit, long step)
{
    for (long divisor = start; divisor &lt;= limit; divisor += step)
        if (dividend % divisor == 0) 
            return false;
    return  true;
}
</code></pre>
<p dir="auto">This partitions the range into <code>available_threads()</code> separate ranges via steps, so each created thread tests each of these sub-ranges, no further thread creation/destruction over the initial creation of threads.</p>
<p dir="auto">Obviously I then need (a) some mechanism of knowing when all threads have run their own loops to completion and never found a divisor for the dividend (so tested number is indeed prime) and (b) a way of a thread returning or signalling immediately when it has found a divisor (tested number is composite) so that main code can then immediately terminate the other threads and return false.</p>
<p dir="auto">Among all the QtConcurrent methods for filtering/mapping/reducing I have not figured whether/how this algorithmic behaviour could be executed as stated?  (Btw, any solution which creates a list of all the numbers from 2 to <em>limit</em> and then filters/reduces them takes too much space by definition; and anything which creates more total threads ever greater than <code>available_threads()</code> is presumed to be "slow" because of thread creation overhead.)</p>
<p dir="auto">For the avoidance of doubt: I am interested in Qt methods to test performance.  If there is, say, a <code>std</code> library function which tells you whether a number is prime even by using the host's threads for you, that is not what I am looking for :)</p>
]]></description><link>https://forum.qt.io/topic/165087/is-qtconcurrent-suitable-for-this-concurrent-parallel-algorithm</link><generator>RSS for Node</generator><lastBuildDate>Mon, 14 Sep 2026 09:28:23 GMT</lastBuildDate><atom:link href="https://forum.qt.io/topic/165087.rss" rel="self" type="application/rss+xml"/><pubDate>Sat, 12 Sep 2026 09:02:38 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Mon, 14 Sep 2026 08:42:07 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/simonschroeder">@<bdi>SimonSchroeder</bdi></a><br />
[Before we start: you might like to change what you have written either to swap the <code>true</code>/<code>false</code>s or change <code>isPrime</code> to <code>isComposite</code> :) ]</p>
<p dir="auto">The underlying issue here I am trying to examine is: the simplest way to write the algorithm is just to have a single loop running from 2 to <em>limit</em>, just as you have here.  And have each division check done in some thread.  Theoretically with 4 threads you get 4 times the speed.  <strong>However</strong>, I <em>presume</em> that --- even if we allow the pre-creation of the 4 threads and re-use --- there is some overhead for running the division on a  thread: something for setting up/starting off the division code and something for finishing/returning the result.  Right?  And that may be considerable, even larger than, the time taken to execute a single division in its body.</p>
<p dir="auto">That indicates to me that I need to write an algorithm which partitions the domain into 4 quarters and just gets each of 4 threads to do a loop over its 1/4th of the numbers, to minimize the thread start/end overheads.</p>
<p dir="auto">Now, it may be that your <code>#pragma omp parallel for shared(limit,dividend,divisor,isPrime)</code> does just that.  I don't know because you have not said how it works.  That would be a good start.  But I am <em>guessing</em> that, even if it does so, it naively partitions the range into the lowest first quarter of numbers, the middle two quarters and the highest quarter, e.g. first quarter would run from <code>2</code> to <code>2 + limit / 4</code>.  This would be fine if the body were, say, counting the number of iterations in each thread's quarter of the range.  Each quarter does just the same amount of work as every other.</p>
<p dir="auto">But that is not true for prime test by trial division.  When a number is going to be prime each quarter must run through all its range till they all fail, fine.  But when a number is going to be composite we are going to find a factor and stop (all threads).  The problem is that a target composite dividend is going to be <em>much</em> more likely to have a factor in the first quarter (<code>3</code>, <code>5</code>, <code>7</code>, <code>11</code>, ...) than in a higher quarter.  Let's say a dividend is going to have <code>11</code> as its lowest factor.  We will have to wait for the lowest quarter range to perform 4 iterations before it meets <code>11</code> and we can terminate that and the other threads.  Over a large range of numbers, the algorithm --- at least when it examines a composite dividend  --- will degenerate into sequential/single-threaded performance.</p>
<p dir="auto">My intention is to partition the domain into quarters a different way:</p>
<ul>
<li>Thread 1: <code>3</code>, <code>11</code>, <code>19</code>, ...</li>
<li>Thread 2: <code>5</code>, <code>13</code>, <code>21</code>, ...</li>
<li>Thread 3: <code>7</code>, <code>15</code>, <code>23</code>, ...</li>
<li>Thread 4: <code>9</code>, <code>17</code>, <code>25</code>, ...</li>
</ul>
<p dir="auto">This <em>spreads out</em> the lower numbers, which are going to be the most common factors, fairly equally between the threads.  It will be more common to find a (low) factor early in <em>one</em> of the threads.</p>
<p dir="auto">Now, I don't know, but does your <code>#pragma omp parallel for shared(limit,dividend,divisor,isPrime)</code> do that, or can it be made to do that?  Because without guidance it would have no reason to do so, rather than just divide it into sequential quarters?</p>
<p dir="auto">And when you do have a (pre-created) thread to use on a core: just what is the "overhead" to, say, start, run and complete a piece of target code in it?  I don't know how/what the processor or the code has to do when asked to execute a small piece of code in a thread?</p>
]]></description><link>https://forum.qt.io/post/840141</link><guid isPermaLink="true">https://forum.qt.io/post/840141</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Mon, 14 Sep 2026 08:42:07 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Mon, 14 Sep 2026 06:09:22 GMT]]></title><description><![CDATA[<p dir="auto">Well, maybe a small side quest: The easiest method to make the algorithm parallel might be using OpenMP:</p>
<pre><code>long dividend = ...;  // the number to test for primality
long limit = sqrt(test);
bool isPrime = false;
#pragma omp parallel for shared(limit,dividend,divisor,isPrime)
for (long divisor = 2; divisor &lt;= limit; divisor++)
    if (dividend % divisor == 0)
        isPrime = true;
return  isPrime;
</code></pre>
<p dir="auto">You have to turn on OpenMP (something like <code>-fopenmp</code>) to make it run in parallel. OpenMP automatically scales with the number of cores and you can even choose a scheduling algorithm and chunk size to optimize it further. Quick testing can be done by setting OpenMP environment variables to change the defaults.</p>
<p dir="auto">The equivalent in Qt is actually <code>QtConcurrent</code>. <code>QtConcurrent::run</code> doesn't really help because most of the work is still on your shoulders, but map-and-reduce is perfect for this. <code>QtConcurrent</code> actually starts a thread pool and does not oversubscribe your CPU cores (even with <code>QtConcurrent::run</code>). It is also not constantly starting new threads, but reuses threads from the thread pool. You can do similar things with <code>QThread</code> if you just start the event loop for each worker thread and push "tasks" by using <code>QMetaObject::invokeMethod</code>.</p>
<p dir="auto">You might have noticed that for the OpenMP example I did not include early termination (yet). IIRC with OpenMP this is a little bit more complicated and you might have to write <code>continue</code> to run empty loops for "early terminations". Usually (independent of OpenMP), it is sufficient to have a boolean variable accessible to all threads and let one thread toggle it if it finds a solution. It does not have to be atomic. For early termination you probably don't care if termination is immediate or slightly delayed (until the cores have synched up). At least, you don't have to pay for the overhead of an atomic in every single loop iteration.</p>
<p dir="auto">If you are looking for a fast solution, you can get some inspiration from Dave Plummer's Prime Drag Race. Dave Plummer is a retired Microsoft engineer on YouTube. In the Prime Drag Race people competed/compete with different programming languages to write the fastest program.</p>
]]></description><link>https://forum.qt.io/post/840137</link><guid isPermaLink="true">https://forum.qt.io/post/840137</guid><dc:creator><![CDATA[SimonSchroeder]]></dc:creator><pubDate>Mon, 14 Sep 2026 06:09:22 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Sun, 13 Sep 2026 12:52:01 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/jksh">@<bdi>JKSH</bdi></a> said in <a href="/post/840128">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">Then, apply QtConcurrent::map() to your QList&lt;Range&gt;. This is the idiomatic way^ to express your algorithm above.</p>
</blockquote>
<p dir="auto">We shall see.  For now I am creating <code>QtConcurrent::run()</code>s for each available core, per my approach earlier, passing in parameters to each one for what "range" to test.  No map/filter/reduce, no ranges as ranges.  When that's working/timed, I might compare against the list approach.  What we are all agreeing, apparently, is not to do the naïve "create a thread for each test division (<em>not</em> with a loop to test a bunch of them)", and let QtConcurrent figure out threads &amp; pool for it.  Which to me is the "logical" way a noob might approach it, but I <em>assume</em> grossly slow.</p>
<blockquote>
<p dir="auto">QFutureWatcher is your friend.</p>
</blockquote>
<p dir="auto">Ah, OK.</p>
<blockquote>
<p dir="auto">Once an instance of your threadFunc() starts running, it normally can't be terminated before completion (in contrast, QThread offers a terminate() function). So, you'll need to add some kind of escape hatch, like a global Boolean flag that your for-loops check</p>
</blockquote>
<p dir="auto">Ah, OK again.  Yes, surprises me if basic <code>QThread</code> does allow forceful terminate.</p>
<blockquote>
<p dir="auto">BTW, it's pointless/wasteful to test even divisors (except 2). Just check if your number is divisible by 2 before starting any threads, and then let your threads only test odd divisors. This halves the maximum number of divisors that they need to test.</p>
</blockquote>
<p dir="auto">Of course, already in code but not shown earlier.</p>
]]></description><link>https://forum.qt.io/post/840129</link><guid isPermaLink="true">https://forum.qt.io/post/840129</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Sun, 13 Sep 2026 12:52:01 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Sun, 13 Sep 2026 12:47:29 GMT]]></title><description><![CDATA[<p dir="auto">Back to using Qt Concurrent for your algorithm:</p>
<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/jonb">@<bdi>JonB</bdi></a> said in <a href="/post/840110">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">Among all the QtConcurrent methods for filtering/mapping/reducing I have not figured whether/how this algorithmic behaviour could be executed as stated? (Btw, any solution which creates a list of all the numbers from 2 to limit and then filters/reduces them takes too much space by definition</p>
</blockquote>
<p dir="auto">Instead of a list of all numbers to test, generate a list of ranges ("arithmetic progressions" in maths parlance) to test:</p>
<pre><code>struct Range {
    long start;
    long limit;
    long step;
};
</code></pre>
<p dir="auto">Then, apply <code>QtConcurrent::map()</code> to your <code>QList&lt;Range&gt;</code>. This is the idiomatic way^ to express your algorithm above (both are equivalent).</p>
<p dir="auto">BTW, it's pointless/wasteful to test even divisors (except <code>2</code>). Just check if your number is divisible by 2 before starting any threads, and then let your threads only test odd divisors. This halves the maximum number of divisors that they need to test.</p>
<blockquote>
<p dir="auto">Obviously I then need (a) some mechanism of knowing when all threads have run their own loops to completion and never found a divisor for the dividend (so tested number is indeed prime) and (b) a way of a thread returning or signalling immediately when it has found a divisor (tested number is composite)</p>
</blockquote>
<p dir="auto"><code>QFutureWatcher</code> is your friend.</p>
<blockquote>
<p dir="auto">so that main code can then immediately terminate the other threads and return false.</p>
</blockquote>
<p dir="auto">Once an instance of your <code>threadFunc()</code> starts running, it normally can't be terminated before completion (in contrast, QThread offers a <code>terminate()</code> function). So, you'll need to add some kind of escape hatch, like a global Boolean flag that your for-loops check before performing a division. I'm not sure how much overhead this adds -- benchmark and see.</p>
<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/jonb">@<bdi>JonB</bdi></a> said in <a href="/post/840111">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">(Looks like <code>QtConcurrent::run()</code> in <em>Run With Promise</em> mode?)</p>
<p dir="auto">Is this the (only/right) way to use QtConcurrent for my proposed algorithm?</p>
</blockquote>
<p dir="auto">As you've seen above, Run, Map, and Filter are all viable. I'd imagine that the global Boolean flag has equal or lower overhead than cancelling a Run via a QPromise. However, the latter is more "self-contained" so you could run your prime-check algorithm on multiple dividends simultaneously.</p>
<p dir="auto">^ P.S. To be extra idiomatic, you could use map-reduce instead of map, where the reduce function checks the results of all your threads and makes the final declaration of "Prime" or "Not Prime". But I think this is over-engineering. Plus, it doesn't fit nicely with the requirement to terminate computation early once a factor is found.</p>
]]></description><link>https://forum.qt.io/post/840128</link><guid isPermaLink="true">https://forum.qt.io/post/840128</guid><dc:creator><![CDATA[JKSH]]></dc:creator><pubDate>Sun, 13 Sep 2026 12:47:29 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Sun, 13 Sep 2026 11:54:11 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/igkh">@<bdi>IgKh</bdi></a><br />
I read a whole book just on the Riemann Hypothesis a few years ago.  I can honestly say it was the most boring book I have ever read ;-)</p>
]]></description><link>https://forum.qt.io/post/840127</link><guid isPermaLink="true">https://forum.qt.io/post/840127</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Sun, 13 Sep 2026 11:54:11 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Sun, 13 Sep 2026 10:17:00 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/jonb">@<bdi>JonB</bdi></a> said in <a href="/post/840122">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">But, if I understand correctly, it (a) only tells me whether a number is probably prime, (b) relies (at least in some variants) on a still unproven Riemann hypothesis and (c) does not give me factors if it decides a number is composite.</p>
</blockquote>
<p dir="auto">We are going a little off-topic, but this is close to the area of my professional capacity so why not! Rabin-Miller is indeed probabilistic, but the error probability can be arbitrarily bounded by running more iterations of the test, driving the chance of mistake to being negligible. This is similar in concept to other probabilistic data structure and algorithms, like bloom filters. The Riemann hypothesis thing is not actually relied on if you accept non-determinism, so the matter of assumptions holding is not pertinent to the size of the numbers.</p>
<p dir="auto">It's true that RM is just a test, it doesn't help to factorize integers - at least not directly. It is however very important in cryptography, since many cryptosystems rely on generating very large random prime numbers. And by very large I mean things like 2,048 or 4,096 bits. A loop of drawing a random number from a range and then testing it for primality is the best we have in practice, so a fast (even if only, say, 99.9999% accurate) test is extremely useful.</p>
]]></description><link>https://forum.qt.io/post/840124</link><guid isPermaLink="true">https://forum.qt.io/post/840124</guid><dc:creator><![CDATA[IgKh]]></dc:creator><pubDate>Sun, 13 Sep 2026 10:17:00 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Sun, 13 Sep 2026 08:00:58 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/igkh">@<bdi>IgKh</bdi></a> said in <a href="/post/840117">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">I'd probably use a filter-reduce operation on a custom iterator class (to not actually allocate a list of all numbers 2..sqrt(n)) - <a href="https://doc.qt.io/qt-6/qtconcurrentfilter.html#concurrent-filter-reduce" target="_blank" rel="noopener noreferrer nofollow ugc">https://doc.qt.io/qt-6/qtconcurrentfilter.html#concurrent-filter-reduce</a></p>
</blockquote>
<p dir="auto">Yes, I did wonder whether a "lazy-generator" of the numbers might be usable for the QtConcurrent methods.  I might try this as a timing test against my proposed approach outlined earlier.</p>
<blockquote>
<p dir="auto">the most efficient way to test primality of truly large numbers is the Rabin-Miller test</p>
</blockquote>
<p dir="auto">I had a read through this.  I am aware there are other algorithms which perform better than trial division.  But, if I understand correctly, it (a) only tells me whether a number is <em>probably</em> prime, (b) relies (at least in some variants) on a still unproven <em>Riemann hypothesis</em> and (c) does not give me factors if it decides a number is composite.  I am uncomfortable about all of these!  Of course, I do realise my intended range of 64-bit numbers is trivially small and doubtless the assumptions do hold in this domain, but I still don't like the idea of a mathematical solution which says a 3 sided shape is "probably" a triangle... ;-)</p>
]]></description><link>https://forum.qt.io/post/840122</link><guid isPermaLink="true">https://forum.qt.io/post/840122</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Sun, 13 Sep 2026 08:00:58 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Sat, 12 Sep 2026 12:45:44 GMT]]></title><description><![CDATA[<p dir="auto">I'd probably use a filter-reduce operation on a custom iterator class (to not actually allocate a list of all numbers <code>2..sqrt(n)</code>) - <a href="https://doc.qt.io/qt-6/qtconcurrentfilter.html#concurrent-filter-reduce" target="_blank" rel="noopener noreferrer nofollow ugc">https://doc.qt.io/qt-6/qtconcurrentfilter.html#concurrent-filter-reduce</a></p>
<p dir="auto">Also - I know you didn't ask for alternative algorithms, but for the benefit of anyone reading the thread later that might be interested, the most efficient way to test primality of truly large numbers is the <a href="https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test" target="_blank" rel="noopener noreferrer nofollow ugc">Rabin-Miller test</a></p>
]]></description><link>https://forum.qt.io/post/840117</link><guid isPermaLink="true">https://forum.qt.io/post/840117</guid><dc:creator><![CDATA[IgKh]]></dc:creator><pubDate>Sat, 12 Sep 2026 12:45:44 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Sat, 12 Sep 2026 09:22:52 GMT]]></title><description><![CDATA[<p dir="auto">Thinking aloud about my own post.  Funny how typing it all in makes you think down a logical route... :)</p>
<p dir="auto">I was thinking/hoping in terms of calling a QtConcurrent method for each division to test and having it just do the <code>dividend % divisor == 0</code> for one pair of numbers.  But as I said that will presumably incur too much overhead.  If I want to use QtConcurrent: I know (I think) that I only want <code>available_threads()</code> number of threads created, so I could use it to create those with <code>threadFunc(long start, long limit, long step)</code> as the function to run.  I am then using QtConcurrent to handle the early or final termination code of all threads (the "outer" loop) rather than at the "do one division" (the "inner" loop).  (Looks like <code>QtConcurrent::run()</code> in <em>Run With Promise</em> mode?)</p>
<p dir="auto">Is this the (only/right) way to use QtConcurrent for my proposed algorithm?</p>
]]></description><link>https://forum.qt.io/post/840111</link><guid isPermaLink="true">https://forum.qt.io/post/840111</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Sat, 12 Sep 2026 09:22:52 GMT</pubDate></item></channel></rss>