<?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>Tue, 22 Sep 2026 10:19:36 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, 21 Sep 2026 10:35:04 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/simonschroeder">@<bdi>SimonSchroeder</bdi></a><br />
Hmm, further complications.  I went back to ChatGPT and carefully phrased what we are trying to do/asking about, where we think this case of a boolean and the way it is set/read means we do not need atomicity and can just use, say, a <code>volatile</code> shared variable.  The gist of its answer is:</p>
<blockquote>
<p dir="auto">In this situation std::atomic&lt;bool&gt; is required if you want the program to be correct according to the C++ memory model.</p>
</blockquote>
<blockquote>
<p dir="auto">The important distinction is between what the hardware happens to do and what C++ guarantees.</p>
</blockquote>
<blockquote>
<p dir="auto">In C++, a non-atomic object cannot safely be accessed concurrently this way. That's a data race, and a data race means undefined behaviour.</p>
<p dir="auto">It doesn't matter that:<br />
[...]</p>
</blockquote>
<blockquote>
<p dir="auto">volatile does not fix it. volatile is about observable memory accesses, primarily for things such as memory-mapped hardware; it isn't a thread-synchronisation mechanism.</p>
</blockquote>
<p dir="auto">and concludes:</p>
<blockquote>
<p dir="auto">But atomicity is still required for the read/write relationship.</p>
<p dir="auto">So the short answer is:</p>
<p dir="auto">Yes, atomic&lt;bool&gt; is required for a correct C++ program here. No, volatile bool is not a valid replacement. But you absolutely don't need to pay for an atomic load on every iteration — checking it periodically is a very reasonable optimisation for your algorithm.</p>
</blockquote>
<p dir="auto">(It having suggested only calling <code>done.load(std::memory_order_relaxed)</code> once every so many iterations round the loop, just as you &amp; I talked about.  I have implemented that for every 256 iterations in each thread and that gives me acceptably similar timing now.)</p>
<p dir="auto">So I take that it while my non-<code>atomic</code> implementation may <em>appear</em> to work, or may work fine on my particular machine/architecture, it is at least theoretically not allowed ("Undefined Behaviour") under C++ at least.</p>
<p dir="auto">In a <em>certain</em> sense this is "reassuring"/"simple": instead of having to ponder whether a given "shared" variable and what we do with it (flag, counter, whatever) determines whether I need <code>atomic</code> or not, it seems I just need to use <code>atomic</code> <em>whenever</em> I have cross-thread read/writes.</p>
]]></description><link>https://forum.qt.io/post/840212</link><guid isPermaLink="true">https://forum.qt.io/post/840212</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Mon, 21 Sep 2026 10:35:04 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Mon, 21 Sep 2026 08:58:58 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/simonschroeder">@<bdi>SimonSchroeder</bdi></a><br />
Hi Simon, thanks for your answer. there is a lot to digest here!</p>
<p dir="auto">The variable is a "global" variable, I was expecting that to actually read/write the location not use a register but I see what you mean about the code <em>might</em> hold it only in a register at least for some time.  FWIW, I have marked it <code>volatile</code> and see no speed difference.  Yes I had thought about only checking an atomic every so often through the loop for speed now that I know atomic is so slow.</p>
<blockquote>
<p dir="auto">In your specific case the write does not depend on the previous value and therefore does not have to be atomic.</p>
</blockquote>
<p dir="auto">Indeed.  My situation is many threads (if multiple factors) may <em>set</em> the variable and many threads need to <em>test</em> the variable to exit.  While this is by no means the only algorithm using threads and variables it is one of the most common and simple.  I shall be requerying ChatGPT on why it wanted me to use an atomic and what the speed consequences are.</p>
<blockquote>
<p dir="auto">From my easiest understand if the thread does not have any code to run anymore, it is terminated. So, there needs to be explicit code somewhere that sleeps the thread to wait for further work.</p>
</blockquote>
<blockquote>
<p dir="auto">Otherwise your QThread has to implement it's own method how others can communicate to run some specific function (with arguments).</p>
</blockquote>
<p dir="auto">This quite changes my understanding/guessing of how threads, and Qt's thread pool, work.  I had thought/assumed that, at the OS level, you could initially create a thread that was totally empty/idle and get a "handle" back from it.  Then whenever you liked you could have a function/some code and just tell the idle thread to execute that; and when it finished that code it would return to be quite empty/idle, ready for re-use.  Now you are saying that, effectively, you must have some code for the thread always to be executing right from that start, and for "re-use" you must have explicit code in it constantly "waiting" for a "message" which it interprets for setting off some execution, after which it returns to its "waiting loop".  All of which probably does not exist for the underlying OS thread but is provided at the lowest level by <code>QThread</code>.</p>
<p dir="auto">It also means that where I read</p>
<blockquote>
<p dir="auto">QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread.</p>
</blockquote>
<blockquote>
<p dir="auto">Another way to make code run in a separate thread, is to subclass QThread and reimplement run().<br />
In that example, the thread will exit after the run function has returned. There will not be any event loop running in the thread unless you call exec().</p>
</blockquote>
<p dir="auto">I interpreted "if you don't call <code>exec()</code> there will be no event loop" as meaning a thread (<code>QThread</code>) does not have <em>any</em> code/loop running if you don't call <code>exec()</code>.  You are saying a <code>QThread</code> always has (or should have) a function-execution-request-queue, just it won't have specifically a Qt event loop if no <code>exec()</code>.  You cannot actually completely separate the creation of a thread from what code it will execute, that has to be specified at creation time not later on.  And <code>QThreadPool</code> is to do with marshalling how many of these <code>QThread</code>s are doing work at the same time and sending them "messages" for when to do the next job which they themselves are sitting in a loop waiting for, not for re-using an "idle" thread to do a totally new job somehow.</p>
]]></description><link>https://forum.qt.io/post/840211</link><guid isPermaLink="true">https://forum.qt.io/post/840211</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Mon, 21 Sep 2026 08:58:58 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Mon, 21 Sep 2026 07:30:53 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/840207">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">Ignoring this "memory order" stuff, which seems to be to do with ordering multiple accesses, is the terrible speed because atomic does some kind of "mutex" under the hood, not just a single/fast instruction to access it?</p>
</blockquote>
<p dir="auto">Usually, the mutex is implemented through atomics (and not the other way around). And an atomic is just a single instruction (and it is fast for what it does). However, what might need to happen is synchronization between L1 caches of different cores. This is slow. Though, it's not necessarily the bytes of actual data that is exchanged between the caches, but just the information if something has changed (and only after that the actual data is also sent).</p>
<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/jonb">@<bdi>JonB</bdi></a> said in <a href="/post/840207">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">What exactly do I have to do/protect against concurrent access when?</p>
</blockquote>
<p dir="auto">You definitely have to protect against read-modify-write. The easiest example for this is a counter (or more specific in the context of threads a semaphore). Between reading and writing another thread might have already read and written the same variable. This easily messes up counters if they are not atomic (that's why shared_ptr uses an atomic counter internally). There is even an A/B problem with two variables and two threads; each reading from one variable and writing the other. There is something strange going on here with an instruction ordering that might result in a totally unexpected state (at least on x86). C++26 now also introduced hazard pointers that allow multiple readers, but only a single writer (while nobody else is reading).</p>
<p dir="auto">In your specific case the write does not depend on the previous value and therefore does not have to be atomic. The only thing that might happen without an atomic is that other threads are not immediately informed when a change happens. They might just run a few additional cycles of the loop. You might also just check the atomic boolean variable every 10 loop cycles to get more speed. I am not entirely sure if there is anything about the boolean variable (if it is not atomic) that requires it to be committed to memory eventually (and not just stay a register-only variable). You could mark it as volatile, but that would require to fetch it from memory (or cache) on every single access. That also slows it down.</p>
<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/jonb">@<bdi>JonB</bdi></a> said in <a href="/post/840207">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">Finally, while I am here: what exactly has to be done at runtime when you ask a thread to execute some code (function/lambda)?</p>
</blockquote>
<p dir="auto">From my easiest understand if the thread does not have any code to run anymore, it is terminated. So, there needs to be explicit code somewhere that sleeps the thread to wait for further work. Usually, you'll have something like a task queue–either for a single worker thread or for a thread pool. You cannot just run code in another thread without doing additional work (either it's your own code or it is some library code). With <code>QThread</code> the easiest way is to just use the default <code>run()</code> method which will call <code>exec()</code>. Then, you can add individual work items to that thread's event loop through <code>QMetaObject::invokeMethod()</code>. Otherwise your <code>QThread</code> has to implement it's own method how others can communicate to run some specific function (with arguments). But, that would require that you have a task queue (definitely thread-safe!) where you can store functions to be executed and the worker thread has to get new items from the queue. If nothing is there, it needs to sleep. And either it is woken up when something is put into the queue, or the thread has to wake up repeatedly and poll the task queue. This gets more complicated if you want a thread pool instead. Effectively, you'd be reimplementing either the event loop of <code>QThread</code> or the thread pool of <code>QtConcurrent::run()</code>. Just use those instead if you are already using Qt for threading. For a one-off thread there is also <code>QThread::start()</code> (as you have mentioned), but it needs boiler plate code to clean up after itself (or you just use my small wrapper library for <code>QThread</code>: <a href="https://github.com/SimonSchroeder/QtThreadHelper" target="_blank" rel="noopener noreferrer nofollow ugc">https://github.com/SimonSchroeder/QtThreadHelper</a> ; it is just a single header, but it shows a lot of different corner case you might not have thought about, yet).</p>
]]></description><link>https://forum.qt.io/post/840210</link><guid isPermaLink="true">https://forum.qt.io/post/840210</guid><dc:creator><![CDATA[SimonSchroeder]]></dc:creator><pubDate>Mon, 21 Sep 2026 07:30:53 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Sun, 20 Sep 2026 08:11:44 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/840196">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">I wonder if you'll get a noticeable improvement if you use a non-atomic bool? Since the value always starts as false and the only value that could possibly be written is true, there's no benefit in guarding against race conditions.</p>
</blockquote>
<p dir="auto">Well indeed!  Changing from <code>std::atomic&lt;bool&gt;</code> to just plain <code>bool</code> halved the time to run the algorithm/loop so that it is just the same as if the test were not there.  So now I have some questions... :)</p>
<p dir="auto">I got <code>std::atomic&lt;bool&gt;</code> from my friend ChatGPT, who is never wrong.  He said I could/should use <code>std::memory_order_relaxed</code>.  Reading up on that now:</p>
<blockquote>
<p dir="auto">Atomic operations tagged memory_order_relaxed are not synchronization operations; they do not impose an order among concurrent memory accesses. They only guarantee atomicity and modification order consistency.</p>
</blockquote>
<blockquote>
<p dir="auto">Typical use for relaxed memory ordering is incrementing counters, such as the reference counters of std::shared_ptr, since this only requires atomicity, but not ordering or synchronization</p>
</blockquote>
<p dir="auto">So that part is something to do with the <em>ordering</em> of operations in different threads, which I do not need here.  But what is the underlying behaviour of <code>std::atomic&lt;bool&gt;</code> with <code>store()</code> and <code>load()</code>?  Does a plain <code>std::atomic&lt;bool&gt; flag; flag = true; // or if (flag) ...</code> behave any differently than using <code>store()</code>/<code>load()</code>?  Ignoring this "memory order" stuff, which seems to be to do with ordering multiple accesses, is the terrible speed because <code>atomic</code> does some kind of "mutex" under the hood, not just a single/fast instruction to access it?</p>
<p dir="auto">What <em>exactly</em> do I have to do/protect against concurrent access when?  In the olden days, where "multitasking" meant a single CPU swapping between threads of execution, I had to think about something like the processor swapping in between each individual instruction, but I think not when right in the middle of executing a single instruction.</p>
<p dir="auto">Now presumably a different thread can execute any time, even when the other thread is in mid-instruction?  Why do I care anyway when I have, say, a <code>bool</code> or even <code>int</code> variable which I set in one thread and test in another?  Those are (presumably) set in a single instruction, the reader just sees it either as it was before or afterwards but not in some inconsistent "mid-instruction" state?  And here I don't care if a test in the loop sees a change from another thread this time round or next time round.  I also don't think it matters if two threads simultaneously find their own factors and both set the variable to true (though I agree that might matter in an incrementing counter case)?   Even if the shared variable (still one writer many readers) were a pointer wouldn't a statement which assigned a new value, <code>ptr = new_value;</code>, be a single instruction so a reader executing "during" that would still see the value either as before or after that statement, not half way through writing into the 4/8 bytes comprising the pointer?</p>
<p dir="auto">Finally, while I am here: what exactly has to be done at runtime when you ask a thread to execute some code (function/lambda)?  I assume there are two overheads.  One is from initial construction of a thread/<code>QThread</code>.  If you destroy and recreate you would pay this every time.  But presumably with a thread <em>pool</em> like I am using it re-uses previously created threads?  The second must be whatever has to be done to "start" or "run" the thread with its code, like <code>QThread::start()</code> or <code>run()</code> (say you have subclassed <code>QThread::run()</code> so it does not do any event loop via <code>exec()</code>).  What has to be done/how much overhead is there to just get an (existing) thread to start executing some code?  This is pretty significant if the code just does something really small and simple like a single division and then exits.  Which is why I make each thread do a <em>range</em> of tests instead of one at a time, even though that complicates my algorithm.</p>
]]></description><link>https://forum.qt.io/post/840207</link><guid isPermaLink="true">https://forum.qt.io/post/840207</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Sun, 20 Sep 2026 08:11:44 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Sat, 19 Sep 2026 14:46:29 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/840196">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">?? The size of the list equals available_threads(). Which shouldn't be a really large number on your laptop.</p>
</blockquote>
<p dir="auto">I am so sorry.  I got it <em>fixated</em> in my mind that using <code>mapped()</code> we were going to create actual lists of the numbers in each range, hence all my stuff about large numbers of elements.  <em>Of course</em> this code now approaches it in just the same way as my <code>run()</code>s, the list is just one element, not as many as are in the range, per thread.</p>
<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/jksh">@<bdi>JKSH</bdi></a> said in <a href="/post/840196">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">I wonder if you'll get a noticeable improvement if you use a non-atomic bool? Since the value always starts as false and the only value that could possibly be written is true, there's no benefit in guarding against race conditions.</p>
</blockquote>
<p dir="auto">I took that code straight from an AI, and haven't even bothered to look into it :)  That's what it said I wanted for simplest/fastest for "set in one thread, test in others"  I didn't even look it up, I <em>thought</em> it was implying this is non-mutex.  If you are not convinced I will certainly retest tomorrow with, say, a plain <code>bool</code> and see if that is where it is taking all its time.   In which case we will discuss that... :)</p>
]]></description><link>https://forum.qt.io/post/840197</link><guid isPermaLink="true">https://forum.qt.io/post/840197</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Sat, 19 Sep 2026 14:46:29 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Sat, 19 Sep 2026 14:04:41 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/840191">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<p dir="auto">I would probably make an effort to reduce overhead space/time on having to create all these list elements by using an iterator-function or the new <code>QRangeModel</code> if I used <code>mapped()</code> but didn't bother to rewrite to test that.</p>
<p dir="auto">Since the sort of number I am testing initially is a 64-bit <code>18446744073709551557UL</code>, which I know to be prime, it is fortunate we only have to examine up to its square root, else the pre-created lists would need to be <em>really</em> large :)</p>
</blockquote>
<p dir="auto">?? The size of the list equals <code>available_threads()</code>. Which <em>shouldn't</em> be a <em>really</em> large number on your laptop.</p>
<blockquote>
<p dir="auto">It's an (interesting) shame to discover that the code required to "short-circuit" testing every factor once a factor is found anywhere (required for early-discovered composites) costs as much as all the division tests and hence doubles the time if the target number turns out to be prime.  So if you want the fastest time when a number <em>turns out</em> to be prime don't even try to terminate early if it is not!</p>
</blockquote>
<p dir="auto">I wonder if you'll get a noticeable improvement if you use a non-atomic <code>bool</code>? Since the value always starts as <code>false</code> and the only value that could possibly be written is <code>true</code>, there's no benefit in guarding against race conditions.</p>
<blockquote>
<p dir="auto">(early in my past I wrote for <strong>6502</strong> processor where you had to write division as a loop yourself, I guess it's more efficient these days ;) )</p>
</blockquote>
<p dir="auto">Fun!</p>
]]></description><link>https://forum.qt.io/post/840196</link><guid isPermaLink="true">https://forum.qt.io/post/840196</guid><dc:creator><![CDATA[JKSH]]></dc:creator><pubDate>Sat, 19 Sep 2026 14:04:41 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Sat, 19 Sep 2026 12:40:19 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/jksh">@<bdi>JKSH</bdi></a><br />
Hi <a class="plugin-mentions-user plugin-mentions-a" href="/user/jksh">@<bdi>JKSH</bdi></a>.  I managed to find some time to try your algorithm.</p>
<p dir="auto">After some required changes to it, and making it do the same loop as my existing code using <code>QtConcurrent::run()</code> (e.g. each range should start from <code>3 + thread * 2</code>), I agree timings came out similar.  I would probably make an effort to reduce overhead space/time on having to create all these list elements by using an iterator-function or the new <code>QRangeModel</code> if I used <code>mapped()</code> but didn't bother to rewrite to test that.</p>
<p dir="auto">Since the sort of number I am testing initially is a 64-bit <code>18446744073709551557UL</code>, which I know to be prime, it is fortunate we only have to examine up to its square root, else the pre-created lists would need to be <em>really</em> large :)</p>
<p dir="auto">What I did find interesting while doing is: applying equally whether I use <code>mapped()</code> or <code>run()</code>, the overhead of checking in each thread's loop for whether any other thread has found a factor:</p>
<pre><code>std::atomic&lt;bool&gt; finish_threads{false};

    for (unsigned long divisor = start; divisor &lt;= limit &amp;&amp; !finish_threads.load(std::memory_order_relaxed); divisor += step)
        if (dividend % divisor == 0)
        {
            finish_threads.store(true, std::memory_order_relaxed);
            return false;
        }
    return true;
</code></pre>
<p dir="auto">Just the test of the atomic boolean each time round the loop, done as efficiently as I know how, seems to about double the total elapsed time (for a prime number).  I had not expected that to be as high a cost as the division (early in my past I wrote for <strong>6502</strong> processor where you had to write division as a loop yourself, I guess it's more efficient these days ;) )  It's an (interesting) shame to discover that the code required to "short-circuit" testing every factor once a factor is found anywhere (required for early-discovered composites) costs as much as all the division tests and hence doubles the time if the target number turns out to be prime.  So if you want the fastest time when a number <em>turns out</em> to be prime don't even try to terminate early if it is not!</p>
]]></description><link>https://forum.qt.io/post/840191</link><guid isPermaLink="true">https://forum.qt.io/post/840191</guid><dc:creator><![CDATA[JonB]]></dc:creator><pubDate>Sat, 19 Sep 2026 12:40:19 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Thu, 17 Sep 2026 05:34:18 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/840129">Is QtConcurrent suitable for this concurrent/parallel algorithm?</a>:</p>
<blockquote>
<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....  When that's working/timed, I might compare against the list approach.</p>
</blockquote>
<p dir="auto">To clarify: What I described does EXACTLY the same thing as your multiple <code>QtConcurrent::run()</code> calls, so I'd expect the timing to be the same.</p>
<p dir="auto">It was to show you how to use QtConcurrent::mapped() to run the algorithm that you described (my apologies, my previous post erroneously said <code>map()</code> instead of <code>mapped()</code>). The main difference is that you end up with a single <code>QFuture</code> instead of one QFuture per thread:</p>
<pre><code>struct Range {
    long start;
    long limit;
    long step;
};
bool threadFunc(const Range &amp;range)
{
    for (long divisor = range.start; divisor &lt;= range.limit; divisor += range.step)
        if (dividend % divisor == 0) 
            return false;
    return  true;
}
</code></pre>
<pre><code>// ### Set up and run your threads
int threads = available_threads();  // maybe 8?
QList&lt;Range&gt; ranges;
for (int thread = 0; thread &lt; threads; thread++)
    ranges &lt;&lt; Range{2+thread, limit, threads}; // Or `Range{3+thread, limit, 2*threads};` if you've already tested for evenness earlier

QFuture&lt;bool&gt; future = QtConcurrent::mapped(ranges, threadFunc);


// ### Set up your results monitor
auto watcher = new QFutureWatcher&lt;bool&gt;(someParent);
QObject::connect(watcher, &amp;QFutureWatcher&lt;bool&gt;::resultReadyAt, qApp, [watcher](int index)
{
    if (!watcher-&gt;resultAt(index))
        qDebug() &lt;&lt; "Thread" &lt;&lt; index &lt;&lt; "found a factor";
});
watcher-&gt;setFuture(future);
</code></pre>
<blockquote>
<p dir="auto">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">Indeed. I haven't benchmarked, but I'd expect the cost of setting up a thread to be comparable to the cost of doing a single division in that thread.</p>
<blockquote>
<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)...</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">Thread termination is a foot-gun. It's safe here because you're only reading integers and writing Booleans.</p>
]]></description><link>https://forum.qt.io/post/840172</link><guid isPermaLink="true">https://forum.qt.io/post/840172</guid><dc:creator><![CDATA[JKSH]]></dc:creator><pubDate>Thu, 17 Sep 2026 05:34:18 GMT</pubDate></item><item><title><![CDATA[Reply to Is QtConcurrent suitable for this concurrent&#x2F;parallel algorithm? on Tue, 15 Sep 2026 09:56:24 GMT]]></title><description><![CDATA[<p dir="auto">It's been about 15 years since I have used OpenMP (which means I might be a little fuzzy on the details). Some things might have changed since then (maybe less restrictions).</p>
<p dir="auto">Here is a quick start to OpenMP:</p>
<ul>
<li><code>#pragma omp</code> starts new OpenMP directives</li>
<li><code>#pragma omp parallel</code> starts a new parallel section. This might contain parallel for loops or individual tasks to be run in parallel.</li>
<li><code>#pragma omp for</code> declares a for loop to be executed in parallel. <code>parallel</code> and <code>for</code> can be combined into a single <code>#pragma</code>. (Beware of nested <code>parallel</code> sections!)</li>
<li>The end of the loop effectively has to be constant. <code>vector.size()</code> is not the best idea here; instead copy the vector's size to a variable and use that as an upper bound (which is not a problem in this specific example of primes).</li>
<li>Variables can be <code>private</code>, i.e. every thread has it's own copy of the variable (uninitialized!), <code>firstprivate</code>, i.e. still private, but the original value before the threads started is copied in, <code>lastprivate</code> (I don't remember), or <code>shared</code>. Shared variables is the same variable (without synchronization) for all threads.</li>
</ul>
<p dir="auto">The defaults can be changed by environment variables (e.g. <code>OMP_NUM_THREADS</code> to restrict the number of threads per parallel section) or by calling <code>omp_...()</code> functions. One such thing is the <code>schedule</code> (env var <code>OMP_SCHEDULE</code>): It determines how the loop is split up! It basically boils down (with additional variations) to a <code>static</code> and a <code>dynamic</code> schedule: With the static schedule it is predetermined which parts of the loop are run by which thread and with a dynamic schedule some limited form of work stealing can happen. However, dynamic schedules need additional synchronization to distribute the work. Associated with the schedule is the <em>chunk size</em>: It determines how many loop iterations each work packet does. This is to avoid cache problems when memory access is involved. So, you might have a chunk size of 8. With a static schedule it is still predetermined which chunks each thread gets, but with the dynamic schedule we have work packets of 8 iterations that are some sort of first come first serve (or maybe at first like the static schedule and once a thread has used up its assigned work packets it starts stealing from other threads).</p>
<p dir="auto">You might get lucky with a <code>schedule(static,1)</code>, but in general a chunk size of 1 is not a good idea. Would you be open to a chunk size of 8? Still a lot better if all threads work on the first couple of numbers first. Alternatively, you might try something like this:</p>
<pre><code>#pragma omp parallel shared(limit,dividend,divisor,isPrime)
for(long divisor = omp_get_thread_num(); divisor &lt;= limit; divisor += omp_num_threads())
   ...
</code></pre>
<p dir="auto">Notice that I did not include <code>for</code> in the <code>#pragma omp</code>: I just let every thread run the same loop, but change the start with <code>omp_get_thread_num()</code> (the index of the current thread, starting from 0 -&gt; adapt to start at 2). Unfortunately, <code>omp_get_thread_num()</code> and <code>omp_num_threads()</code> sound quite similar.</p>
<p dir="auto">BTW, for potentially better performance there is also an <code>unroll</code> directive for the pragma.</p>
<p dir="auto">There are official cheat sheets for OpenMP: <a href="https://www.openmp.org/resources/refguides/" target="_blank" rel="noopener noreferrer nofollow ugc">https://www.openmp.org/resources/refguides/</a></p>
]]></description><link>https://forum.qt.io/post/840152</link><guid isPermaLink="true">https://forum.qt.io/post/840152</guid><dc:creator><![CDATA[SimonSchroeder]]></dc:creator><pubDate>Tue, 15 Sep 2026 09:56:24 GMT</pubDate></item><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 Tue, 15 Sep 2026 07:13:36 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 = true;
#pragma omp parallel for shared(limit,dividend,divisor,isPrime)
for (long divisor = 2; divisor &lt;= limit; divisor++)
    if (dividend % divisor == 0)
        isPrime = false;
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>Tue, 15 Sep 2026 07:13:36 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>