<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Threads &#8211; Xojo Programming Blog</title>
	<atom:link href="https://blog.xojo.com/tag/threads/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.xojo.com</link>
	<description>Blog about the Xojo programming language and IDE</description>
	<lastBuildDate>Mon, 02 Mar 2026 23:43:16 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Optimizing Xojo Code, Part 5: Threads and UserInterfaceUpdate</title>
		<link>https://blog.xojo.com/2026/03/02/optimizing-xojo-code-part-5-threads-and-userinterfaceupdate/</link>
		
		<dc:creator><![CDATA[Gabriel Ludosanu]]></dc:creator>
		<pubDate>Mon, 02 Mar 2026 23:43:13 +0000</pubDate>
				<category><![CDATA[Fun]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Multithreaded Applications]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[Threads]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=15847</guid>

					<description><![CDATA[In&#160;Part 1, we learned why tight loops with&#160;DoEvents&#160;freeze your UI.&#160;Part 2&#160;showed us Timer controls.&#160;Part 3&#160;moved timers into code.&#160;Part 4&#160;simplified scheduling with&#160;CallLater. But timers have a&#8230;]]></description>
										<content:encoded><![CDATA[
<p>In&nbsp;<a href="https://blog.xojo.com/2025/11/20/optimizing-xojo-code-part-1-getting-started/">Part 1</a>, we learned why tight loops with&nbsp;<code>DoEvents</code>&nbsp;freeze your UI.&nbsp;<a href="https://blog.xojo.com/2025/11/25/optimizing-xojo-code-part-2-using-a-timer-to-keep-the-ui-responsive/">Part 2</a>&nbsp;showed us Timer controls.&nbsp;<a href="https://blog.xojo.com/2026/01/14/optimizing-xojo-code-part-3-programmatic-timers-and-addhandler/">Part 3</a>&nbsp;moved timers into code.&nbsp;<a href="https://blog.xojo.com/2026/02/02/optimizing-xojo-code-part-4-timer-calllater/">Part 4</a>&nbsp;simplified scheduling with&nbsp;<code>CallLater</code>.</p>



<p>But timers have a limit: they still run on the UI thread. If your background work is genuinely heavy (database queries, file I/O, complex calculations), a timer won&#8217;t save you. You need actual background processing and that&#8217;s where threads come in.</p>



<h2 class="wp-block-heading" id="the-core-idea-threads">The Core Idea: Threads</h2>



<p>A thread is a separate execution path that runs outside the UI thread. While your thread does the heavy lifting, the UI stays responsive to clicks, typing, scrolling. When your thread finishes a chunk of work, it notifies the UI thread via&nbsp;<code>UserInterfaceUpdate</code>, and only that callback runs on the main thread.</p>



<p>The rule is simple: threads cannot touch UI controls directly. If you try, you get a crash.&nbsp;<code>UserInterfaceUpdate</code>&nbsp;is your bridge.</p>



<p>For a deeper dive into how Xojo&#8217;s threading model works under the hood, including cooperative vs. preemptive threading, see&nbsp;<a href="https://blog.xojo.com/2024/10/01/cooperative-to-preemptive-weaving-new-threads-into-your-apps/" target="_blank" rel="noreferrer noopener">Cooperative to Preemptive: Weaving New Threads Into Your Apps</a>.</p>



<h2 class="wp-block-heading" id="looking-at-the-code">Let&#8217;s Code</h2>



<p><strong>Prerequisites:</strong>&nbsp;Add a&nbsp;<code>StatusLabel</code>&nbsp;(DesktopLabel), a&nbsp;<code>DesktopButton</code>, and a&nbsp;<code>Thread</code>&nbsp;control. Also define:</p>



<pre class="wp-block-code"><code>kCountTo As Integer = 100</code></pre>



<h3 class="wp-block-heading" id="the-thread-control">The Thread Control</h3>



<p>Drag a&nbsp;<code>Thread</code>&nbsp;from the library into your window and name it&nbsp;<code>BackgroundWorker</code>.</p>



<h3 class="wp-block-heading" id="the-button-start-the-thread">The Button (Start the Thread)</h3>



<p>Place this in the&nbsp;<code>Pressed</code>&nbsp;event of a button:</p>



<pre class="wp-block-code"><code>Sub Pressed()
  If BackgroundWorker.ThreadState = Thread.ThreadStates.NotRunning Then
    BackgroundWorker.Start
  End If
End Sub</code></pre>



<p>This checks if the thread is already running. If not, start it. This prevents multiple threads from piling up if someone clicks fast.</p>



<h3 class="wp-block-heading" id="the-run-method-background-work">The Thread.Run Method (Background Work)</h3>



<p>Implement the&nbsp;<code>Run</code>&nbsp;method on your Thread:</p>



<pre class="wp-block-code"><code>Sub Run()
  For i As Integer = 0 To kCountTo
    
    ' Do background work here. No UI access allowed.
    ' It can be: database query, file read, API call, pretty much anything that might block "freeze" the UI of the app
    
    ' Prepare a Dictionary payload for the UI
    Var info As New Dictionary
    info.Value("progress") = i
    info.Value("message") = "working"
    Me.AddUserInterfaceUpdate(info)
    
    ' Sleep (optional)
    Thread.SleepCurrent(10)   // Sleep 10 ms
  Next
End Sub</code></pre>



<p>The key line is&nbsp;<code>Me.AddUserInterfaceUpdate(info)</code>. This queues data for the UI thread to process. Each call adds one item to a queue, and the UI thread drains it in&nbsp;<code>UserInterfaceUpdate</code>.</p>



<h3 class="wp-block-heading" id="the-userinterfaceupdate-method-ui-sync">The Thread.UserInterfaceUpdate Method (UI Sync)</h3>



<p>Implement this event to handle updates from the thread:</p>



<pre class="wp-block-code"><code>Sub UserInterfaceUpdate(data() As Dictionary)
  ' Runs on the main UI thread. Safe to update controls here.
  
  ' Guard against empty or malformed data
  If data = Nil Or data.Count &lt; 0 Then Return
  
  Var d As Dictionary = data(0)
  
  ' Extract the progress value safely
  Var progress As Integer = 0
  If d.HasKey("progress") Then
    progress = d.Value("progress").IntegerValue
  End If
  
  ' Update the UI
  StatusLabel.Text = progress.ToString
  
  ' Mark completion when we hit the target
  If progress &gt;= kCountTo Then
    StatusLabel.Text = "done"
  End If
End Sub</code></pre>



<p><strong>Important notes:</strong></p>



<ul class="wp-block-list">
<li><code>data()</code>&nbsp;is an array of Dictionaries.</li>



<li>Always check&nbsp;<code>HasKey</code>&nbsp;before accessing a value to avoid runtime errors.</li>



<li>Use&nbsp;<code>.IntegerValue</code>&nbsp;(or&nbsp;<code>.StringValue</code>, etc.) to safely extract values.</li>



<li>This runs on the UI thread, so it is safe to update&nbsp;<code>StatusLabel</code>&nbsp;and any other visual controls.</li>
</ul>



<h2 class="wp-block-heading" id="how-it-works">How It Works</h2>



<ol class="wp-block-list">
<li><strong>Button press:</strong>&nbsp;Click the button and the thread starts.</li>



<li><strong>Background loop:</strong>&nbsp;The thread iterates from 0 to&nbsp;<code>kCountTo</code>, sleeping 10 ms each step. After each step, it queues an update.</li>



<li><strong>Responsiveness:</strong>&nbsp;While the thread works, you can still interact with the rest of your application. No freezing.</li>
</ol>



<h2 class="wp-block-heading" id="a-note-on-thread-safety">A Note on Thread Safety</h2>



<p>Threads are powerful but risky if misused. Here is the boundary:</p>



<ul class="wp-block-list">
<li><strong>Safe in Run():</strong>&nbsp;Anything that doesn&#8217;t touch UI controls. File I/O, database queries, calculations, network calls.</li>



<li><strong>Unsafe in Run():</strong>&nbsp;Reading or writing UI control properties directly.&nbsp;<code>StatusLabel.Text = ...</code>&nbsp;is a no no!</li>



<li><strong>Safe in UserInterfaceUpdate():</strong>&nbsp;All UI control access. This runs on the main thread.</li>
</ul>



<p>If you forget this rule and try to update a label from inside&nbsp;<code>Run()</code>, your app will crash with a <a href="https://documentation.xojo.com/api/language/runtime.html#runtime">ThreadAccessingUIException</a>. Instead pass data through&nbsp;<code>AddUserInterfaceUpdate</code>.</p>



<h2 class="wp-block-heading" id="when-to-use-threads-vs-timers">When to Use Threads vs. Timers</h2>



<p>Use timers for:</p>



<ul class="wp-block-list">
<li>Short, frequent tasks (10-50 ms ticks).</li>



<li>Simple progress updates.</li>



<li>Cases where you are just deferring work a bit.</li>
</ul>



<p>Use threads for:</p>



<ul class="wp-block-list">
<li>Long-running operations (seconds, minutes, hours).</li>



<li>Genuinely blocking work (I/O, network, heavy calculations).</li>



<li>Multiple independent background tasks.</li>
</ul>



<p>In this series, we moved from blocking the UI to using timers on the UI thread, then to actual background threads. Each approach solves a different problem.</p>



<h2 class="wp-block-heading" id="wrapping-up">Wrapping Up</h2>



<p>Threads are the heavy artillery of responsive design. They run independent of the UI and communicate safely via&nbsp;<code>UserInterfaceUpdate</code>. Once you grasp the boundary between thread code and UI code, you can build applications that never freeze, no matter how much work is happening behind the scenes.</p>



<p>See the&nbsp;<a href="https://documentation.xojo.com/api/language/threading/thread.html">Thread documentation</a>&nbsp;for more details on priority, stack size, and advanced patterns.</p>



<p>Until then, happy threading!</p>



<p><em>Gabriel is a digital marketing enthusiast who loves coding with Xojo to create cool software tools for any platform. He is always eager to learn and share new ideas!</em></p>



<ul class="wp-block-social-links has-normal-icon-size is-content-justification-center is-layout-flex wp-container-core-social-links-is-layout-16018d1d wp-block-social-links-is-layout-flex"><li class="wp-social-link wp-social-link-facebook  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.facebook.com/goxojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M12 2C6.5 2 2 6.5 2 12c0 5 3.7 9.1 8.4 9.9v-7H7.9V12h2.5V9.8c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.8l-.4 2.9h-2.3v7C18.3 21.1 22 17 22 12c0-5.5-4.5-10-10-10z"></path></svg><span class="wp-block-social-link-label screen-reader-text">Facebook</span></a></li>

<li class="wp-social-link wp-social-link-x  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://x.com/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M13.982 10.622 20.54 3h-1.554l-5.693 6.618L8.745 3H3.5l6.876 10.007L3.5 21h1.554l6.012-6.989L15.868 21h5.245l-7.131-10.378Zm-2.128 2.474-.697-.997-5.543-7.93H8l4.474 6.4.697.996 5.815 8.318h-2.387l-4.745-6.787Z" /></svg><span class="wp-block-social-link-label screen-reader-text">X</span></a></li>

<li class="wp-social-link wp-social-link-linkedin  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.linkedin.com/company/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M19.7,3H4.3C3.582,3,3,3.582,3,4.3v15.4C3,20.418,3.582,21,4.3,21h15.4c0.718,0,1.3-0.582,1.3-1.3V4.3 C21,3.582,20.418,3,19.7,3z M8.339,18.338H5.667v-8.59h2.672V18.338z M7.004,8.574c-0.857,0-1.549-0.694-1.549-1.548 c0-0.855,0.691-1.548,1.549-1.548c0.854,0,1.547,0.694,1.547,1.548C8.551,7.881,7.858,8.574,7.004,8.574z M18.339,18.338h-2.669 v-4.177c0-0.996-0.017-2.278-1.387-2.278c-1.389,0-1.601,1.086-1.601,2.206v4.249h-2.667v-8.59h2.559v1.174h0.037 c0.356-0.675,1.227-1.387,2.526-1.387c2.703,0,3.203,1.779,3.203,4.092V18.338z"></path></svg><span class="wp-block-social-link-label screen-reader-text">LinkedIn</span></a></li>

<li class="wp-social-link wp-social-link-github  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://github.com/topics/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M12,2C6.477,2,2,6.477,2,12c0,4.419,2.865,8.166,6.839,9.489c0.5,0.09,0.682-0.218,0.682-0.484 c0-0.236-0.009-0.866-0.014-1.699c-2.782,0.602-3.369-1.34-3.369-1.34c-0.455-1.157-1.11-1.465-1.11-1.465 c-0.909-0.62,0.069-0.608,0.069-0.608c1.004,0.071,1.532,1.03,1.532,1.03c0.891,1.529,2.341,1.089,2.91,0.833 c0.091-0.647,0.349-1.086,0.635-1.337c-2.22-0.251-4.555-1.111-4.555-4.943c0-1.091,0.39-1.984,1.03-2.682 C6.546,8.54,6.202,7.524,6.746,6.148c0,0,0.84-0.269,2.75,1.025C10.295,6.95,11.15,6.84,12,6.836 c0.85,0.004,1.705,0.114,2.504,0.336c1.909-1.294,2.748-1.025,2.748-1.025c0.546,1.376,0.202,2.394,0.1,2.646 c0.64,0.699,1.026,1.591,1.026,2.682c0,3.841-2.337,4.687-4.565,4.935c0.359,0.307,0.679,0.917,0.679,1.852 c0,1.335-0.012,2.415-0.012,2.741c0,0.269,0.18,0.579,0.688,0.481C19.138,20.161,22,16.416,22,12C22,6.477,17.523,2,12,2z"></path></svg><span class="wp-block-social-link-label screen-reader-text">GitHub</span></a></li>

<li class="wp-social-link wp-social-link-youtube  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.youtube.com/c/XojoInc" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M21.8,8.001c0,0-0.195-1.378-0.795-1.985c-0.76-0.797-1.613-0.801-2.004-0.847c-2.799-0.202-6.997-0.202-6.997-0.202 h-0.009c0,0-4.198,0-6.997,0.202C4.608,5.216,3.756,5.22,2.995,6.016C2.395,6.623,2.2,8.001,2.2,8.001S2,9.62,2,11.238v1.517 c0,1.618,0.2,3.237,0.2,3.237s0.195,1.378,0.795,1.985c0.761,0.797,1.76,0.771,2.205,0.855c1.6,0.153,6.8,0.201,6.8,0.201 s4.203-0.006,7.001-0.209c0.391-0.047,1.243-0.051,2.004-0.847c0.6-0.607,0.795-1.985,0.795-1.985s0.2-1.618,0.2-3.237v-1.517 C22,9.62,21.8,8.001,21.8,8.001z M9.935,14.594l-0.001-5.62l5.404,2.82L9.935,14.594z"></path></svg><span class="wp-block-social-link-label screen-reader-text">YouTube</span></a></li></ul>



<p><strong>Optimizing Code Series:</strong></p>



<ul class="wp-block-list">
<li><a href="https://blog.xojo.com/2025/11/20/optimizing-xojo-code-part-1-getting-started/" target="_blank" rel="noreferrer noopener">Optimizing Xojo Code, Part 1: Getting Started</a></li>



<li><a href="https://blog.xojo.com/2025/11/25/optimizing-xojo-code-part-2-using-a-timer-to-keep-the-ui-responsive/" target="_blank" rel="noreferrer noopener">Optimizing Xojo Code, Part 2: Using a Timer to Keep the UI Responsive</a></li>



<li><a href="https://blog.xojo.com/2026/01/14/optimizing-xojo-code-part-3-programmatic-timers-and-addhandler/" target="_blank" rel="noreferrer noopener">Optimizing Xojo Code, Part 3: Programmatic Timers and AddHandler</a></li>



<li><a href="https://blog.xojo.com/2026/02/02/optimizing-xojo-code-part-4-timer-calllater/" target="_blank" rel="noreferrer noopener">Optimizing Xojo Code, Part 4: Timer.CallLater</a></li>



<li><a href="https://blog.xojo.com/2026/03/02/optimizing-xojo-code-part-5-threads-and-userinterfaceupdate/" target="_blank" rel="noreferrer noopener">Optimizing Xojo Code, Part 5: Threads and UserInterfaceUpdate</a></li>
</ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Implementing a Non-Blocking Image Processor with Xojo Threads</title>
		<link>https://blog.xojo.com/2025/08/28/implementing-a-non-blocking-image-processor-with-xojo-threads/</link>
		
		<dc:creator><![CDATA[Gabriel Ludosanu]]></dc:creator>
		<pubDate>Thu, 28 Aug 2025 14:56:33 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Mac]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Dictionary]]></category>
		<category><![CDATA[FolderItem]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Picture]]></category>
		<category><![CDATA[Threads]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=15302</guid>

					<description><![CDATA[Have you ever written an app that needs to do some heavy lifting, like processing a big batch of files? Maybe you click a button,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Have you ever written an app that needs to do some heavy lifting, like processing a big batch of files? Maybe you click a button, and suddenly your entire app just … stops. The cursor turns into a spinning wheel, the windows won’t respond, and your users are left wondering if it crashed. It’s a frustrating experience, but don’t worry, there’s a solution:&nbsp;<a href="https://documentation.xojo.com/api/language/threading/thread.html" target="_blank" rel="noreferrer noopener">Threads</a>!</p>



<p>Let&#8217;s build a simple but incredibly powerful Desktop app: a threaded image resizer. This tool will let you pick a folder of images and resize them all without ever locking up the app. It’s a perfect showcase of how easy and effective <a href="https://documentation.xojo.com/topics/threading/index.html" data-type="link" data-id="https://documentation.xojo.com/topics/threading/index.html" target="_blank" rel="noreferrer noopener">threading</a> can be in Xojo.</p>



<p>Let’s get started!</p>



<h4 class="wp-block-heading" id="step-1-designing-the-user-interface">Step 1: Designing the User Interface</h4>



<p>First things first, let’s lay out our app’s window. We’re going for a clean and simple design. All you need to do is create a new Xojo Desktop project and add the following controls from the Library onto your main window:</p>



<ol class="wp-block-list">
<li><strong>DesktopButton</strong>: This will be our “start” button. The user will click this to select a folder and begin the resizing process. Let’s set its&nbsp;<code>Caption</code>&nbsp;to “Select folder &amp;&amp; Start”.</li>



<li><strong>DesktopProgressBar</strong>: This will give the user visual feedback on the progress of the resizing operation.</li>



<li><strong>DesktopLabel</strong>: We’ll use this label to display status updates, like which file is currently being processed or when the job is complete. Let’s call it&nbsp;<code>StatusLabel</code>.</li>
</ol>



<p>Your app layout should look something like this:</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="692" src="https://blog.xojo.com/wp-content/uploads/2025/08/thread_image_resizer_1-1024x692.jpg" alt="" class="wp-image-15303" srcset="https://blog.xojo.com/wp-content/uploads/2025/08/thread_image_resizer_1-1024x692.jpg 1024w, https://blog.xojo.com/wp-content/uploads/2025/08/thread_image_resizer_1-300x203.jpg 300w, https://blog.xojo.com/wp-content/uploads/2025/08/thread_image_resizer_1-768x519.jpg 768w, https://blog.xojo.com/wp-content/uploads/2025/08/thread_image_resizer_1.jpg 1525w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h4 class="wp-block-heading" id="step-2-adding-the-magic-ingredient-the-thread">Step 2: Adding the Magic Ingredient: The Thread</h4>



<div class="wp-block-group is-nowrap is-layout-flex wp-container-core-group-is-layout-ad2f72ca wp-block-group-is-layout-flex">
<p>Now for the star of the show! Go to the Library and find the&nbsp;<code>Thread</code>&nbsp;object. Drag and drop one onto your window. By default, it might be named&nbsp;<code>Thread1</code>, but I’ve renamed mine to&nbsp;<code>ResizeThread</code>&nbsp;to make its purpose crystal clear. This object is where our background work will happen.</p>



<figure class="wp-block-image size-full is-resized"><img decoding="async" width="298" height="287" src="https://blog.xojo.com/wp-content/uploads/2025/08/thread_image_resizer_2.jpg" alt="" class="wp-image-15304" style="width:500px"/></figure>
</div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Quick note on thread types: Cooperative threads (the default) share a single CPU core with the main/UI thread and other cooperative threads. Preemptive threads can run on separate CPU cores and deliver true parallelism for CPU-bound work. More info on this subject: <a href="https://blog.xojo.com/2024/10/01/cooperative-to-preemptive-weaving-new-threads-into-your-apps/" target="_blank" rel="noreferrer noopener">Cooperative to Preemptive: Weaving New Threads into your Apps</a></p>
</blockquote>



<p>Why this project uses Preemptive threads: resizing many images is CPU-bound and benefits from parallel cores without blocking the UI.</p>



<h4 class="wp-block-heading" id="step-3-kicking-off-the-process">Step 3: Kicking Off the Process</h4>



<p>With the UI and thread in place, let’s add the code to get things moving. Double-click the “Select folder &amp; Start” button to add its&nbsp;<code>Pressed</code>&nbsp;event. This is what will run when the user clicks it.</p>



<p>Here’s the code for the&nbsp;<code>Pressed</code>&nbsp;event:</p>



<pre class="wp-block-code"><code>' Ask the user for a source folder (contains images)
Var f As FolderItem = FolderItem.ShowSelectFolderDialog
If f = Nil Then Return ' user cancelled

mSourceFolder = f

' Reset UI
ProgressBar1.Value = 0
StatusLabel.Text = "Starting…"

' Kick off background work!
ResizeThread.Start</code></pre>



<p>Let’s break this down. First, we ask the user to select a folder. If they don’t pick one, we simply exit. If they do, we store the selected folder in a window property called&nbsp;<code>mSourceFolder</code>&nbsp;(<code>Public Property mSourceFolder As FolderItem</code>). We then reset our progress bar and status label and, most importantly, we call&nbsp;<code>ResizeThread.Start</code>. That one simple line tells our thread to wake up and get to work by running its&nbsp;<code>Run</code>&nbsp;event.</p>



<h4 class="wp-block-heading" id="step-4-the-heavy-lifting-in-the-background">Step 4: The Heavy Lifting (in the Background)</h4>



<p>The&nbsp;<code>Run</code>&nbsp;event of the&nbsp;<code>ResizeThread</code>&nbsp;is where the core logic lives. This is where we’ll find, load, resize, and save the images. Remember, the golden rule of threads is:&nbsp;never touch the UI directly from the Run event. Doing so can cause crashes and unpredictable behavior.</p>



<p>Instead, we perform our task and then&nbsp;<em>send a message</em>&nbsp;back to the main thread with an update. We do this using a method called&nbsp;<code>AddUserInterfaceUpdate</code>.</p>



<p>Here’s the&nbsp;<code>Run</code>&nbsp;event code:</p>



<pre class="wp-block-code"><code>' Quick validation up-front
If mSourceFolder = Nil Or Not mSourceFolder.Exists Or Not mSourceFolder.IsFolder Then
  Me.AddUserInterfaceUpdate(New Dictionary("progress":0, "msg":"No folder selected"))
  Return
End If

Try
  ' Ensure output subfolder "&lt;selected&gt;/resized" exists
  Var outFolder As FolderItem = mSourceFolder.Child("resized")
  If Not outFolder.Exists Then outFolder.CreateFolder
  
  ' Build a list of candidate image files.
  ' Note: Using Picture.Open to validate images is simple and robust.
  '       (For very large folders, you could pre-filter by extension first.)
  Var images() As FolderItem
  For Each it As FolderItem In mSourceFolder.Children
    If it = Nil Or it.IsFolder Then Continue ' Ignore subfolders
    Try
      Var p As Picture = Picture.Open(it)
      If p &lt;&gt; Nil Then images.Add(it)
    Catch e As RuntimeException
      ' Non-image or unreadable; skip
    End Try
  Next
  
  Var total As Integer = images.Count
  If total = 0 Then
    Me.AddUserInterfaceUpdate(New Dictionary("progress":0, "msg":"No images found"))
    Return
  End If
  
  ' Resize settings (simple “fit within 800x800” bounding box)
  Const kMaxW As Double = 800.0
  Const kMaxH As Double = 800.0
  
  ' Short delay after each file so the main thread can repaint the UI
  Const kDelayMS As Integer = 50
  
  For i As Integer = 0 To total - 1
    Var src As FolderItem = images(i)
    Try
      ' Load source (immutable)
      Var pic As Picture = Picture.Open(src)
      If pic = Nil Or pic.Width &lt;= 0 Or pic.Height &lt;= 0 Then Continue
      
      ' Compute proportional scale (never upscale)
      Var sW As Double = kMaxW / pic.Width
      Var sH As Double = kMaxH / pic.Height
      Var scale As Double = Min(Min(sW, sH), 1.0)
      
      Var newW As Integer = Max(1, pic.Width * scale)
      Var newH As Integer = Max(1, pic.Height * scale)
      
      ' Render into a new mutable bitmap of the target size
      Var outPic As New Picture(newW, newH)
      outPic.Graphics.DrawPicture(pic, 0, 0, newW, newH, 0, 0, pic.Width, pic.Height)
      
      ' Build a safe base name (strip the last extension; handle dotfiles)
      Var name As String = src.Name
      Var ext As String = name.LastField(".")
      Var baseName As String
      If ext = name Then
        ' No dot in the name
        baseName = name
      Else
        baseName = name.Left(name.Length - ext.Length - 1)
      End If
      If baseName.Trim = "" Then baseName = "image"
      
      ' Save JPEG (fallback PNG if JPEG export not supported)
      Var outFile As FolderItem = outFolder.Child(baseName + "_resized.jpg")
      If Picture.IsExportFormatSupported(Picture.Formats.JPEG) Then
        outPic.Save(outFile, Picture.Formats.JPEG, Picture.QualityHigh) ' adjust the quality of the jpeg here
      Else
        outPic.Save(outFolder.Child(baseName + "_resized.png"), Picture.Formats.PNG)
      End If
      
    Catch io As IOException
      ' Likely a write/permission/disk issue; skip this file
    Catch u As UnsupportedOperationException
      ' Unsupported format/operation on this platform; skip
    End Try
    
    ' Progress + message to the UI (safe handoff)
    Var pct As Integer = ((i + 1) * 100) / total
    Me.AddUserInterfaceUpdate(New Dictionary("progress":pct, _
    "msg":"Resized " + src.Name + " (" + pct.ToString + "%)"))
    
    ' Let the main thread paint the update
    Me.Sleep(kDelayMS, True) ' wakeEarly=True allows early resume when idle
  Next
  
  ' Final UI message
  Me.AddUserInterfaceUpdate(New Dictionary("progress":100, "msg":"Done"))
  
Catch e As RuntimeException
  ' Any unexpected failure: report a friendly error
  Me.AddUserInterfaceUpdate(New Dictionary("progress":0, "msg":"Error: " + e.Message))
End Try</code></pre>



<h4 class="wp-block-heading" id="step-5-receiving-updates-and-safely-changing-the-ui">Step 5: Receiving Updates and Safely Changing the UI</h4>



<p>So, how does the main thread “hear” these updates? Through the&nbsp;<code>UserInterfaceUpdate</code>&nbsp;event on the&nbsp;<code>ResizeThread</code>&nbsp;itself! This event fires on the main thread, making it the one and only safe place to update our controls.</p>



<p>Here’s the code for the&nbsp;<code>UserInterfaceUpdate</code>&nbsp;event:</p>



<pre class="wp-block-code"><code>' This event runs on the main thread – SAFE to update controls here.
If data.Count = 0 Then Return

Var latest As Dictionary = data(data.LastIndex)

If latest.HasKey("progress") Then ProgressBar1.Value = latest.Value("progress")
If latest.HasKey("msg") Then StatusLabel.Text = latest.Value("msg")

' A little bonus: when we are done, open the output folder!
If latest.HasKey("msg") And latest.Value("msg") = "Done" Then
  Var outFolder As FolderItem = mSourceFolder.Child("resized")
  If outFolder &lt;&gt; Nil And outFolder.Exists Then
    outFolder.Open
  End If
End If</code></pre>



<p>In this event, we receive an array of Dictionaries (all the updates that have queued up). We usually only care about the very latest one, so we grab&nbsp;<code>data(data.LastIndex)</code>. Then, we safely access the values from the dictionary and assign them to&nbsp;<code>ProgressBar1.Value</code>&nbsp;and&nbsp;<code>StatusLabel.Text</code>. That’s it!</p>



<h3 class="wp-block-heading" id="conclusion">Conclusion</h3>



<p>And there you have it! A fully functional, non-blocking image resizer. By moving the heavy work to a&nbsp;<code>Thread</code>, we’ve created an application that provides a smooth, professional user experience.</p>



<p>The pattern is simple:</p>



<ol class="wp-block-list">
<li><strong>Start</strong>&nbsp;the task from the main thread (<code>ResizeThread.Start</code>).</li>



<li><strong>Work</strong>&nbsp;inside the thread’s&nbsp;<code>Run</code>&nbsp;event.</li>



<li><strong>Communicate</strong>&nbsp;back to the UI with&nbsp;<code>AddUserInterfaceUpdate</code>.</li>



<li><strong>Update</strong>&nbsp;the UI safely in the&nbsp;<code>UserInterfaceUpdate</code>&nbsp;event.</li>
</ol>



<p>That’s pretty much it! Go ahead, <a href="https://github.com/xolabsro/Thread-Image-Resizer" data-type="link" data-id="https://github.com/xolabsro/Thread-Image-Resizer" target="_blank" rel="noreferrer noopener">download this project’s source code</a> from GitHub, play around with it, and think about how you can use threads in your own applications!</p>



<p>Happy coding!</p>



<p><em>Gabriel is a digital marketing enthusiast who loves coding with Xojo to create cool software tools for any platform. He is always eager to learn and share new ideas!</em></p>



<ul class="wp-block-social-links has-normal-icon-size is-content-justification-center is-layout-flex wp-container-core-social-links-is-layout-16018d1d wp-block-social-links-is-layout-flex"><li class="wp-social-link wp-social-link-facebook  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.facebook.com/goxojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M12 2C6.5 2 2 6.5 2 12c0 5 3.7 9.1 8.4 9.9v-7H7.9V12h2.5V9.8c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.8l-.4 2.9h-2.3v7C18.3 21.1 22 17 22 12c0-5.5-4.5-10-10-10z"></path></svg><span class="wp-block-social-link-label screen-reader-text">Facebook</span></a></li>

<li class="wp-social-link wp-social-link-x  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://x.com/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M13.982 10.622 20.54 3h-1.554l-5.693 6.618L8.745 3H3.5l6.876 10.007L3.5 21h1.554l6.012-6.989L15.868 21h5.245l-7.131-10.378Zm-2.128 2.474-.697-.997-5.543-7.93H8l4.474 6.4.697.996 5.815 8.318h-2.387l-4.745-6.787Z" /></svg><span class="wp-block-social-link-label screen-reader-text">X</span></a></li>

<li class="wp-social-link wp-social-link-linkedin  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.linkedin.com/company/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M19.7,3H4.3C3.582,3,3,3.582,3,4.3v15.4C3,20.418,3.582,21,4.3,21h15.4c0.718,0,1.3-0.582,1.3-1.3V4.3 C21,3.582,20.418,3,19.7,3z M8.339,18.338H5.667v-8.59h2.672V18.338z M7.004,8.574c-0.857,0-1.549-0.694-1.549-1.548 c0-0.855,0.691-1.548,1.549-1.548c0.854,0,1.547,0.694,1.547,1.548C8.551,7.881,7.858,8.574,7.004,8.574z M18.339,18.338h-2.669 v-4.177c0-0.996-0.017-2.278-1.387-2.278c-1.389,0-1.601,1.086-1.601,2.206v4.249h-2.667v-8.59h2.559v1.174h0.037 c0.356-0.675,1.227-1.387,2.526-1.387c2.703,0,3.203,1.779,3.203,4.092V18.338z"></path></svg><span class="wp-block-social-link-label screen-reader-text">LinkedIn</span></a></li>

<li class="wp-social-link wp-social-link-github  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://github.com/topics/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M12,2C6.477,2,2,6.477,2,12c0,4.419,2.865,8.166,6.839,9.489c0.5,0.09,0.682-0.218,0.682-0.484 c0-0.236-0.009-0.866-0.014-1.699c-2.782,0.602-3.369-1.34-3.369-1.34c-0.455-1.157-1.11-1.465-1.11-1.465 c-0.909-0.62,0.069-0.608,0.069-0.608c1.004,0.071,1.532,1.03,1.532,1.03c0.891,1.529,2.341,1.089,2.91,0.833 c0.091-0.647,0.349-1.086,0.635-1.337c-2.22-0.251-4.555-1.111-4.555-4.943c0-1.091,0.39-1.984,1.03-2.682 C6.546,8.54,6.202,7.524,6.746,6.148c0,0,0.84-0.269,2.75,1.025C10.295,6.95,11.15,6.84,12,6.836 c0.85,0.004,1.705,0.114,2.504,0.336c1.909-1.294,2.748-1.025,2.748-1.025c0.546,1.376,0.202,2.394,0.1,2.646 c0.64,0.699,1.026,1.591,1.026,2.682c0,3.841-2.337,4.687-4.565,4.935c0.359,0.307,0.679,0.917,0.679,1.852 c0,1.335-0.012,2.415-0.012,2.741c0,0.269,0.18,0.579,0.688,0.481C19.138,20.161,22,16.416,22,12C22,6.477,17.523,2,12,2z"></path></svg><span class="wp-block-social-link-label screen-reader-text">GitHub</span></a></li>

<li class="wp-social-link wp-social-link-youtube  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.youtube.com/c/XojoInc" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M21.8,8.001c0,0-0.195-1.378-0.795-1.985c-0.76-0.797-1.613-0.801-2.004-0.847c-2.799-0.202-6.997-0.202-6.997-0.202 h-0.009c0,0-4.198,0-6.997,0.202C4.608,5.216,3.756,5.22,2.995,6.016C2.395,6.623,2.2,8.001,2.2,8.001S2,9.62,2,11.238v1.517 c0,1.618,0.2,3.237,0.2,3.237s0.195,1.378,0.795,1.985c0.761,0.797,1.76,0.771,2.205,0.855c1.6,0.153,6.8,0.201,6.8,0.201 s4.203-0.006,7.001-0.209c0.391-0.047,1.243-0.051,2.004-0.847c0.6-0.607,0.795-1.985,0.795-1.985s0.2-1.618,0.2-3.237v-1.517 C22,9.62,21.8,8.001,21.8,8.001z M9.935,14.594l-0.001-5.62l5.404,2.82L9.935,14.594z"></path></svg><span class="wp-block-social-link-label screen-reader-text">YouTube</span></a></li></ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Preemptive Threads Are Here, and They Are… Pretty Good</title>
		<link>https://blog.xojo.com/2024/10/01/preemptive-threads-are-here-and-they-are-pretty-good/</link>
		
		<dc:creator><![CDATA[Kem Tekinay]]></dc:creator>
		<pubDate>Tue, 01 Oct 2024 15:39:29 +0000</pubDate>
				<category><![CDATA[Guest Post]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[2024r3]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Preemptive Threads]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[Threads]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=13693</guid>

					<description><![CDATA[At long last, Xojo has introduced what might be the most-requested feature of all time: preemptive threads. But what are they, when and how do&#8230;]]></description>
										<content:encoded><![CDATA[
<p>At long last, Xojo has introduced what might be the most-requested feature of all time: preemptive threads. But what are they, when and how do you use them, and what are their limitations? Let&#8217;s get into it…</p>



<h2 class="wp-block-heading">In The Beginning</h2>



<p>Threads have been a part of of the Xojo language for a long time, and by now experienced users know the basics: subclass a <code>Thread</code>, fill in the <code>Run</code> event, then call <code>Start</code>. The code in <code>Run</code> will execute independently from the rest of your code leaving your app responsive while it does work in the background.</p>



<p>Mostly.</p>



<p>See, until now, a <code>Thread</code> was only &#8220;cooperative&#8221;, meaning it ran alongside your main code with the framework deciding when to switch between them and how long each should execute. While the main code was running, the <code>Thread</code> code was paused, and while the <code>Thread</code> was running, the main code was paused.</p>



<p>Think of it like standing before two devices that perform different functions when cranked, but only having one crank available. You run the first machine for a bit, then the other, then back to the first, until they are done. And you do it really, really fast.</p>



<p>This worked pretty well when your goal was, say, to keep your user interface responsive. You could spin long-running code into a <code>Thread</code>, then present the results once it finished.</p>



<p>But it was inadequate if your objective was to speed up some intense process, or the code in your <code>Thread</code> did not present logical places to yield time back to your main code. In the former scenario, you were better off not using a <code>Thread</code>, or perhaps using <code>Worker</code> (a severely limited earlier attempt at allowing simultaneous processing), while in the latter you would have to manually yield back processing time, leading to even slower operation.</p>



<h2 class="wp-block-heading">In The Now</h2>



<p>Cooperative threads are fine for many tasks, but when you need something that truly runs independently within your app, a &#8220;preemptive&#8221; thread is required.</p>



<p>A preemptive thread spins off onto another core in your machine, which probably has at least four, and runs there entirely isolated from other threads. It&#8217;s like launching a separate, mini-app that you can share information with.</p>



<p>The limitations that apply to cooperative threads drop away. Since it runs on a different core, it cannot slow down or interfere with your main code, and will run as fast as its core will allow.</p>



<h2 class="wp-block-heading">Challenging Times</h2>



<p>This sounds almost too good to be true, but it&#8217;s not without its challenges. While cooperative threads were rather easy to work with, preemptive threads require an extra layer of thought and awareness for Xojo users.</p>



<p>When a cooperative thread&#8217;s code is running, you know nothing else is, so you don&#8217;t have to worry about, say, updating a <code>Dictionary</code> or removing an element from an array. But with preemptive threads, code runs simultaneously with other code so you cannot just update that <code>Dictionary</code> if there is a chance that the main code, or another preemptive thread, might be doing it too.</p>



<p>Consider this example.</p>



<pre class="wp-block-code"><code>// In our thread
If MyArray.Count = 0 And FinishUp Then
  Exit
Else
  Process MyArray.Pop
End If

//////////////////////////////

// In the main code
FinishUp = True
MyArray.Add 1</code></pre>



<p>You might think the thread is going to process the last element and then exit its loop because <code>FinishUp</code> was set to <code>True</code>, but with preemptive threads we have to be aware of <a href="https://en.wikipedia.org/wiki/Race_condition">race conditions</a> where the order of actions is unpredictable. Here, the main code could set <code>FinishUp</code> to <code>True</code>, and the thread could see that <code>MyArray</code> was empty and exit before the main code could add the last element. Conditions can change at literally any instant, even in the middle of a single line of code.</p>



<p>Fortunately, there are ways to protect against this and you must use them to ensure orderly operation and avoid surprises.</p>



<h2 class="wp-block-heading">Know Your Type</h2>



<p>The first step is creating a preemptive thread, and Xojo&#8217;s implementation is pretty straightforward. Rather than introducing a unique class, you can continue to work with the existing <code>Thread</code> by setting its new <code>Type</code> property to <code>Thread.Types.Preemptive</code>. The <code>Type</code> can be set when instantiating the <code>Thread</code> or from within its running code. You can even switch types at will, although once running, the <code>Type</code> can only be changed from within the <code>Thread</code>.</p>



<p>Example:</p>



<pre class="wp-block-code"><code>// A subclass of Thread called PThread

MyThread = New PThread
PThread.Type = Thread.Types.Preemptive
PThread.Start</code></pre>



<p>Or within the <code>Run</code> event, you could do this:</p>



<pre class="wp-block-code xojo"><code>Me.Type = Thread.Types.Preemptive</code></pre>



<p>You can also set <code>Type</code> through the Inspector after dragging a <code>Thread</code> to a window.</p>



<h2 class="wp-block-heading">Protect Yourself</h2>



<p>Now that you have a preemptive thread ready to go, you have to think about how to protect common resources. Xojo has done a good job of making a lot of the framework safe, but that just means your app shouldn&#8217;t crash if, say, the <code>Thread</code> tries to manipulate a variable at the same time as other code. It&#8217;s up to you to make sure one area of your app doesn&#8217;t clobber the changes made by another.</p>



<p>Consider this code that maintains a <code>Dictionary</code> of Integer arrays.</p>



<pre class="wp-block-code"><code>// Thread code
Var arr() As Integer

If MyDictionary.HasKey(x) Then
  arr = MyDictionary.Value(x)
Else
  MyDictionary.Value(x) = arr
End If

arr.Add 1

//////////////////////////////

// Main code
If Not MyDictionary.HasKey(x) Then
  Var arr() As Integer
  MyDictionary.Value(x) = arr
End If</code></pre>



<p>Run this long enough and you&#8217;re going to wonder why some data got lost. Why? Because both the <code>Thread</code> and main code might be checking for the key at the exact same instant and filling it in when it&#8217;s not found. If the <code>Thread</code> does it first, the main code will almost instantly replace it with an empty array.</p>



<p>Instead, you should use a <code>Semaphore</code> or <code>CriticalSection</code> to make sure code is protected.</p>



<p>You&#8217;d first instantiate one of these in a common property like a <code>Window</code> or <code>Module</code>. (I&#8217;m using <code>Semaphore</code> here, but it works the same for <code>CriticalSection</code>.)</p>



<pre class="wp-block-code Xojo"><code>MySemaphore = New Semaphore
MySemaphore.Type = Thread.Types.Preemptive</code></pre>



<p>Notice the new <code>Type</code> property? It must match the one in <code>Thread</code> and can be used between the main code and a <code>Thread</code> or between same-typed threads. (This is one of the limitations of Xojo&#8217;s implementation: you cannot share a <code>Semaphore</code> or <code>CriticalSection</code> between preemptive and cooperative threads.)</p>



<p>The example can be updated like this:</p>



<pre class="wp-block-code"><code>// Thread code
Var arr() As Integer

MySemaphore.Signal

If MyDictionary.HasKey(x) Then
  arr = MyDictionary.Value(x)
Else
  MyDictionary.Value(x) = arr
End If

MySemaphore.Release

arr.Add 1

//////////////////////////////

// Main code
MySemaphore.Signal

If Not MyDictionary.HasKey(x) Then
  Var arr() As Integer
  MyDictionary.Value(x) = arr
End If

MySemaphore.Release</code></pre>



<p>This will force either the main code or <code>Thread</code> to wait for the other to complete before continuing, ensuring proper order and avoiding the race condition.</p>



<h2 class="wp-block-heading">Limitations</h2>



<p>Using preemptive threads comes with certain restrictions. The biggest one is the aforementioned inability to share a <code>Semaphore</code> or <code>CriticalSection</code> with a cooperative thread. The other is the same as in a cooperative thread: you cannot update a user interface component directly instead relying on the <code>UserInterfaceUpdate</code> mechanism (more on that below).</p>



<p>If you are setting up multiple threads to work on different parts of some object, that may crash hard depending on the type of object. For example, writing to the same file or different parts of a <code>MemoryBlock</code> is fine, but updating a <code>Picture</code> may not be. In those cases, you will have to get creative.</p>



<h2 class="wp-block-heading">What&#8217;s It Good For?</h2>



<p>Choosing preemptive threads over cooperative means that you either have some code that needs to truly run in the background that would otherwise interfere with you user interface, or you have some large task that can be logically processed in parts.</p>



<h3 class="wp-block-heading">Window Service</h3>



<p>In the former case, the easiest technique might be to drag a <code>Thread</code> to your window, set its <code>Type</code>, and implement the <code>Run</code> event. It can be started from within the window either through a manual process like a pressing a button, or automatically when the window opens.</p>



<p>Just like with a cooperative thread, you can send data back to your window using the <code>AddUserInterfaceUpdate</code> method and implementing the <code>UserInterfaceUpdate</code> event.</p>



<h3 class="wp-block-heading">Splitting It Up</h3>



<p>If your task involves something that can be split up into logical chunks, I encourage you to look at my <code>ThreadPool</code> module, accessible through the Xojo Examples or <a href="https://github.com/ktekinay/Xojo-ThreadPool/tree/develop">my GitHub page</a>. (The latter has a README with more details.)</p>



<p>The ideal usage for <code>ThreadPool</code> is when you have some data that can be processed in sections. For example, suppose you wanted to count the vowels in a large file. You could subclass <code>ThreadPool</code> and implement its <code>Process</code> event to count one block. You would then send the file into your subclass in chunks of, say, 256k each and gather the results.</p>



<p>The benefit of <code>ThreadPool</code>, among other things, is that it will handle the coordination for you so the dangers of using preemptive threads are minimized. You still have to consider how to send your results back to your main code safely, perhaps using <code>Semaphore</code>/<code>CriticalSection</code> or the <code>AddUserInterfaceUpdate</code> method, but each block can be considered independently of the others.</p>



<p>(A big thanks to MVP Anthony Cyphers for writing the example included with Xojo.)</p>



<h2 class="wp-block-heading">Juggling Chainsaws</h2>



<p>The power of preemptive threads is clear, but the potential pitfalls can be serious. Unless you&#8217;re very careful, you can easily create bugs that may not be readily apparent, and may take hours or even days to track down. (I say this from unfortunate experience.) Unless you have a compelling reason to take on that challenge, don&#8217;t bother.</p>



<p>What I&#8217;m trying to say is, if a cooperate thread does the job adequately, there is no need to introduce the headache that preemptive threads can bring.</p>



<p>But if you do have a legitimate need, like a long-running process that needs to run quickly without blocking your UI, go for it, just be careful.</p>



<p>In any case, it&#8217;s great that we finally have that option.</p>



<p><em>Kem Tekinay is a Mac consultant and programmer who has been using Xojo since its first release to create custom solutions for clients. He is the author of the popular utilities <a href="http://www.mactechnologies.com/index.php?page=downloads#tftpclient" target="_blank" rel="noreferrer noopener">TFTP Client</a> and <a href="http://www.mactechnologies.com/index.php?page=downloads#regexrx" target="_blank" rel="noreferrer noopener">RegExRX</a> (both written with Xojo) and lives in Connecticut with his wife Lisa, and their cat.</em></p>



<p>Need More Information? Read more about <a href="https://documentation.xojo.com/api/language/thread.html#thread-type" target="_blank" rel="noreferrer noopener">preemptive threads</a> in the Xojo Documentation and <a href="https://blog.xojo.com/2024/10/01/cooperative-to-preemptive-weaving-new-threads-into-your-apps/" target="_blank" rel="noreferrer noopener">Blog</a>. Or read about <a href="https://blog.xojo.com/2024/09/05/using-semaphores-to-manage-resources/" target="_blank" rel="noreferrer noopener">Semaphore</a> and <a href="https://blog.xojo.com/2024/09/18/using-criticalsection-to-manage-resources/" target="_blank" rel="noreferrer noopener">CriticalSection</a>, also on the Xojo Blog.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Cooperative to Preemptive: Weaving New Threads into your Apps</title>
		<link>https://blog.xojo.com/2024/10/01/cooperative-to-preemptive-weaving-new-threads-into-your-apps/</link>
		
		<dc:creator><![CDATA[William Yu]]></dc:creator>
		<pubDate>Tue, 01 Oct 2024 15:31:59 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[2024r3]]></category>
		<category><![CDATA[Concurrency Management]]></category>
		<category><![CDATA[Multithreaded Applications]]></category>
		<category><![CDATA[Preemptive Threads]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[Threads]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=13606</guid>

					<description><![CDATA[Our latest Xojo update introduces a new thread type that maximizes the potential of your multi-core systems. This new preemptive thread model enhances efficiency and&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Our latest Xojo update introduces a new thread type that maximizes the potential of your multi-core systems. This new preemptive thread model enhances efficiency and responsiveness, allowing for improved multitasking and resource management while delivering significant performance gains. In this post, we’ll explore the benefits of this upgrade, delve into the implementation details, and guide you on how to fully utilize the new preemptive threading capabilities.</p>



<h2 class="wp-block-heading">Threading Models</h2>



<p><strong>Cooperative Threads</strong>: This is the threading model that Xojo has traditionally supported and continues to offer. In this model, threads must voluntarily yield control at specific points that we define. This ensures that most operations in Xojo code are thread-safe, as we manage access to MemoryBlocks, Arrays, etc. However, this approach can lead to inefficiencies if a thread fails to yield, potentially blocking UI, and because only one thread runs at a time, it doesn&#8217;t fully utilize multiple cores or truly run in parallel.</p>



<p><strong>Preemptive Threads</strong>: Introduced in Xojo 2024r3, this new thread type allows threads to be interrupted at any point, enhancing responsiveness and fully utilizing multiple cores. While this model provides significant performance improvements, it also introduces new challenges. Because threads can be interrupted at any time, you&#8217;ll need to be more diligent about locking resources, such as MemoryBlocks and Arrays, to avoid potential race conditions.</p>



<h2 class="wp-block-heading">Using Preemptive Threads</h2>



<p>We&#8217;ve added a new <a href="https://documentation.xojo.com/api/language/thread.html#thread-type" target="_blank" rel="noreferrer noopener">Thread.Type</a> property that allows you to switch your threads to the new preemptive thread model, here&#8217;s how you can start one up:</p>



<pre class="wp-block-code xojo"><code>Thread1.Type = Threads.Types.Preemptive
Thread1.Start</code></pre>



<p>You can set this property either before starting your thread or while the thread is running. However, if changing it while the thread is active, it must be done safely from within the running thread itself, and not externally.</p>



<pre class="wp-block-code"><code>Event Window1.Opening
  // Start the thread and setup the type in the Run event instead
  Thread1.Start
End Event

Sub Thread1.Run
  Me.Type = Threads.Types.Preemptive
  // Run a very long process preemptively.
  newMemBlock = memBlock.Compress
  
  Me.Type = Threads.Types.Cooperative
  // Switching to cooperative mode and modifying a shared array safely.
  mySharedArray.Add("New item")
End Sub</code></pre>



<h2 class="wp-block-heading">Concurrency and Synchronization</h2>



<p>As mentioned earlier, cooperative threads avoid many of the issues that arise with preemptive threads, since we control when thread switching occurs. With preemptive threads, however, you can no longer safely modify things, like shared arrays, the same way you could before with cooperative threads. To manage this, you&#8217;ll need to use tools like <code>CriticalSections</code> and <code>Semaphores</code> more frequently to protect your shared resources.</p>



<p>The challenge lies in efficiently supporting both threading models while enabling the main thread to synchronize with either type. To address this, we’ve added a new Type property to <code>CriticalSection</code> and <code>Semaphores</code>, which must match the thread type you’re using to protect shared resources.</p>



<pre class="wp-block-code"><code>// Imagine the main thread and two additional threads all trying to access a Dictionary simultaneously.
Sub RunTest
  Thread1.Type = Thread.Types.Preemptive
  Thread2.Type = Thread.Types.Preemptive

  CSLock = New CriticalSection
  // Since we are using this CriticalSection in preemptive threads,
  // the synchronization type must be compatible.
  CSLock.Type = Thread1.Type

  Thread1.Start
  Thread2.Start

  Do
    CSLock.Enter
    MyDictionary.RemoveAll
    CSLock.Leave
  Loop
End Sub

Sub Thread1.Run
  Do
    CSLock.Enter
    MyDictionary.Value("Random1") = Rnd
    CSLock.Leave
  Loop
End Sub

Sub Thread2.Run
  Do
    CSLock.Enter
    MyDictionary.Value("Random2") = Rnd
    CSLock.Leave
  Loop
End Sub</code></pre>



<h2 class="wp-block-heading">What things are thread-safe?</h2>



<p>We’ve updated our framework to safeguard areas that were previously not preemptive thread-safe. For the most part, our entire framework is now safe for concurrent use with preemptive threads, with a few exceptions like XojoScript and Runtime.IterateObjects. When sharing resources such as MemoryBlocks, Dictionaries, or Arrays among threads, you may need to use <code>CriticalSections</code> or <code>Semaphores</code> to ensure safe access. However, if you&#8217;re only reading from these resources without modifying them, synchronization is not required. You&#8217;ll be happy to know that calling <code>Thread.AddUserInterfaceUpdate</code> from a preemptive thread is also safe.</p>



<h2 class="wp-block-heading">Performance Considerations</h2>



<p>With the ability to switch your threads to preemptive, there are some performance factors to consider. While running 100 threads at once might seem appealing, it often leads to over-utilizing your system’s resources. For optimal efficiency, it’s best to limit the number of threads to match the number of available cores. To assist with this, we’ve introduced the new <a href="https://documentation.xojo.com/api/os/system.html#system-corecount" target="_blank" rel="noreferrer noopener">System.CoreCount</a>, which helps you determine the number of cores on your system.</p>



<p>While Xojo&#8217;s framework doesn’t shield you from every potential issue, we do handle synchronization for key operations like object creation and destruction. However, you may notice these actions are slower in preemptive threads due to the extra synchronization required.</p>



<h2 class="wp-block-heading">Usage and Examples</h2>



<p>There’s no question that preemptive threads offer significant advantages, and when used correctly, they can greatly enhance your app&#8217;s performance. Check out our threading example projects included with the 2024r3 release to see preemptive threads in action and enjoy weaving these new threads into your future apps!</p>



<p><em>A special thanks to our MVPs for their invaluable help in refining and testing this new feature! Be sure to check out the new ThreadPool example for some practical, real-world use cases and read MVP Kem Tekinay&#8217;s blog post <a href="https://blog.xojo.com/2024/10/01/preemptive-threads-are-here-and-they-are-pretty-good/" target="_blank" rel="noreferrer noopener">Preemptive Threads Are Here and They Are &#8230;. Pretty Good</a>.</em></p>



<p>Need More Information? Read more about <a href="https://documentation.xojo.com/api/language/thread.html#thread-type" target="_blank" rel="noreferrer noopener">preemptive threads</a> in the Xojo Documentation and <a href="https://blog.xojo.com/tag/preemptive-threads/" target="_blank" rel="noreferrer noopener">Blog</a>. Or read about <a href="https://blog.xojo.com/2024/09/05/using-semaphores-to-manage-resources/" target="_blank" rel="noreferrer noopener">Semaphore</a> and <a href="https://blog.xojo.com/2024/09/18/using-criticalsection-to-manage-resources/" target="_blank" rel="noreferrer noopener">CriticalSection</a>.</p>



<p><em><em><em>William Yu grew up in Canada learning to program BASIC on a Vic-20. He is Xojo’s resident Windows and Linux engineer, among his many other skills. Some may say he has joined the dark side here in the USA, but he will always be a Canadian at heart.</em></em></em></p>



<ul class="wp-block-social-links has-normal-icon-size is-content-justification-center is-layout-flex wp-container-core-social-links-is-layout-16018d1d wp-block-social-links-is-layout-flex"><li class="wp-social-link wp-social-link-facebook  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.facebook.com/goxojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M12 2C6.5 2 2 6.5 2 12c0 5 3.7 9.1 8.4 9.9v-7H7.9V12h2.5V9.8c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.8l-.4 2.9h-2.3v7C18.3 21.1 22 17 22 12c0-5.5-4.5-10-10-10z"></path></svg><span class="wp-block-social-link-label screen-reader-text">Facebook</span></a></li>

<li class="wp-social-link wp-social-link-x  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://x.com/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M13.982 10.622 20.54 3h-1.554l-5.693 6.618L8.745 3H3.5l6.876 10.007L3.5 21h1.554l6.012-6.989L15.868 21h5.245l-7.131-10.378Zm-2.128 2.474-.697-.997-5.543-7.93H8l4.474 6.4.697.996 5.815 8.318h-2.387l-4.745-6.787Z" /></svg><span class="wp-block-social-link-label screen-reader-text">X</span></a></li>

<li class="wp-social-link wp-social-link-linkedin  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.linkedin.com/company/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M19.7,3H4.3C3.582,3,3,3.582,3,4.3v15.4C3,20.418,3.582,21,4.3,21h15.4c0.718,0,1.3-0.582,1.3-1.3V4.3 C21,3.582,20.418,3,19.7,3z M8.339,18.338H5.667v-8.59h2.672V18.338z M7.004,8.574c-0.857,0-1.549-0.694-1.549-1.548 c0-0.855,0.691-1.548,1.549-1.548c0.854,0,1.547,0.694,1.547,1.548C8.551,7.881,7.858,8.574,7.004,8.574z M18.339,18.338h-2.669 v-4.177c0-0.996-0.017-2.278-1.387-2.278c-1.389,0-1.601,1.086-1.601,2.206v4.249h-2.667v-8.59h2.559v1.174h0.037 c0.356-0.675,1.227-1.387,2.526-1.387c2.703,0,3.203,1.779,3.203,4.092V18.338z"></path></svg><span class="wp-block-social-link-label screen-reader-text">LinkedIn</span></a></li>

<li class="wp-social-link wp-social-link-github  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://github.com/topics/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M12,2C6.477,2,2,6.477,2,12c0,4.419,2.865,8.166,6.839,9.489c0.5,0.09,0.682-0.218,0.682-0.484 c0-0.236-0.009-0.866-0.014-1.699c-2.782,0.602-3.369-1.34-3.369-1.34c-0.455-1.157-1.11-1.465-1.11-1.465 c-0.909-0.62,0.069-0.608,0.069-0.608c1.004,0.071,1.532,1.03,1.532,1.03c0.891,1.529,2.341,1.089,2.91,0.833 c0.091-0.647,0.349-1.086,0.635-1.337c-2.22-0.251-4.555-1.111-4.555-4.943c0-1.091,0.39-1.984,1.03-2.682 C6.546,8.54,6.202,7.524,6.746,6.148c0,0,0.84-0.269,2.75,1.025C10.295,6.95,11.15,6.84,12,6.836 c0.85,0.004,1.705,0.114,2.504,0.336c1.909-1.294,2.748-1.025,2.748-1.025c0.546,1.376,0.202,2.394,0.1,2.646 c0.64,0.699,1.026,1.591,1.026,2.682c0,3.841-2.337,4.687-4.565,4.935c0.359,0.307,0.679,0.917,0.679,1.852 c0,1.335-0.012,2.415-0.012,2.741c0,0.269,0.18,0.579,0.688,0.481C19.138,20.161,22,16.416,22,12C22,6.477,17.523,2,12,2z"></path></svg><span class="wp-block-social-link-label screen-reader-text">GitHub</span></a></li>

<li class="wp-social-link wp-social-link-youtube  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.youtube.com/c/XojoInc" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M21.8,8.001c0,0-0.195-1.378-0.795-1.985c-0.76-0.797-1.613-0.801-2.004-0.847c-2.799-0.202-6.997-0.202-6.997-0.202 h-0.009c0,0-4.198,0-6.997,0.202C4.608,5.216,3.756,5.22,2.995,6.016C2.395,6.623,2.2,8.001,2.2,8.001S2,9.62,2,11.238v1.517 c0,1.618,0.2,3.237,0.2,3.237s0.195,1.378,0.795,1.985c0.761,0.797,1.76,0.771,2.205,0.855c1.6,0.153,6.8,0.201,6.8,0.201 s4.203-0.006,7.001-0.209c0.391-0.047,1.243-0.051,2.004-0.847c0.6-0.607,0.795-1.985,0.795-1.985s0.2-1.618,0.2-3.237v-1.517 C22,9.62,21.8,8.001,21.8,8.001z M9.935,14.594l-0.001-5.62l5.404,2.82L9.935,14.594z"></path></svg><span class="wp-block-social-link-label screen-reader-text">YouTube</span></a></li></ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Updating the User Interface with the New Thread Class</title>
		<link>https://blog.xojo.com/2019/11/18/updating-the-ui-with-the-new-thread-class/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Mon, 18 Nov 2019 10:00:12 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Threads]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[User Interface]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=6263</guid>

					<description><![CDATA[With Xojo 2019R2, everything related to updating the UI is much simpler thanks to the new UserInterfaceUpdate event in the Thread class.]]></description>
										<content:encoded><![CDATA[<p>Xojo 2019R2 has a lot of new features and enhancements, including the simplification of updating the User Interface in apps from threads running in combination with the main app thread. Doing that in previous releases required the use of a thread in combination with a Timer, for example.<span id="more-6263"></span></p>
<p>With Xojo 2019R2, everything related to updating the UI is much simpler thanks to the new <code>UserInterfaceUpdate</code> event in the Thread class. This provides, as an Array of Dictionaries, all the values we need to pass along from the <code>Run</code> event of the running Thread.</p>
<p><img decoding="async" class="aligncenter wp-image-6264 size-large" src="https://blog.xojo.com/wp-content/uploads/2019/11/Xojo-Threads-API-2-1-1024x751.png" alt="" width="1024" height="751" srcset="https://blog.xojo.com/wp-content/uploads/2019/11/Xojo-Threads-API-2-1-1024x751.png 1024w, https://blog.xojo.com/wp-content/uploads/2019/11/Xojo-Threads-API-2-1-300x220.png 300w, https://blog.xojo.com/wp-content/uploads/2019/11/Xojo-Threads-API-2-1-768x563.png 768w, https://blog.xojo.com/wp-content/uploads/2019/11/Xojo-Threads-API-2-1.png 1456w" sizes="(max-width: 1024px) 100vw, 1024px" /></p>
<p>In order to add new values to these dictionaries, we only need to call the <code>AddUserInterfaceUpdate</code> method, providing as parameter a <code>Pair</code>.</p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-6265 size-large" src="https://blog.xojo.com/wp-content/uploads/2019/11/Xojo-Thread-API-2-Project-1024x612.png" alt="" width="1024" height="612" srcset="https://blog.xojo.com/wp-content/uploads/2019/11/Xojo-Thread-API-2-Project-1024x612.png 1024w, https://blog.xojo.com/wp-content/uploads/2019/11/Xojo-Thread-API-2-Project-300x179.png 300w, https://blog.xojo.com/wp-content/uploads/2019/11/Xojo-Thread-API-2-Project-768x459.png 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></p>
<p>The first (left) value of this pair will be the one acting as the Key for the Dictionary, while the second value of the pair (right) will be the value itself we want to forward to the main thread in order to update our user interface.</p>
<p>In addition, the overloaded <code>AddUserInterfaceUpdate</code> method also accepts a Dictionary as a parameter.</p>
<p>The two ways we can use the new thread class are the same available in previous releases:</p>
<ul>
<li>Draging and dropping an object from the Library panel to the Tray in the Window Layout, so the IDE creates a new instance that we can use to implement the <code>Run</code> and, now, also the <code>UserInterfaceUpdate</code> events. The <code>Run</code> event is the one intended to run the code usually associated with a long task, so it doesn&#8217;t <em>freeze</em> the responsiveness of the rest of the app (mainly the user interaction or user interface refreshes). The <code>UserInterfaceUpdate</code> event is the new Event whose parameter will provide all the data we are interested in previously added from the <code>Run</code> event calling the <code>AddUserInterfaceUpdate</code> method. That is: every time we call the <code>AddUserInterfaceUpdate</code> method, the Thread will fire its <code>UserInterfaceUpdate</code> event. Think about this as a <em>bridge</em> between our Thread and the main app thread.</li>
<li>The second approach is the one we use when creating the Thread instances from code. In this case, the solution is simple and is the one we usually use to <em>delegate</em> the code to execute in the Action event of the Timer class. <code>AddHandler</code> sets the method we want to execute in substitution of the <code>UserInterfaceUpdate</code> event handler of a Thread instance. As usual, make sure that the delegated method has the right signature: receiving a Thread object as its first parameter and the data we are interested in as the second parameter.</li>
</ul>
<p><iframe loading="lazy" title="Threads en Xojo 2019R2 y Posterior" width="500" height="375" src="https://www.youtube.com/embed/XHLL5hCQSSo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe></p>
<p>The example project available <a href="https://bit.ly/2Ni156h">here</a>, shows the implementation of both cases, how the Threads sends the data to update the user interface and how such data is received and accessed in the corresponding Thread Event Handler or delegated Method.</p>
<p>As you can see in the example, the user interface is responsive to the user interaction while the two threads do their work.</p>
<p>Easier and faster!</p>
<p><em data-rich-text-format-boundary="true">Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, GuancheID, AXControlGrid, AXImageCanvas, Markdown Parser for Xojo, and HTMLColorizer for Xojo among others.</em></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Supporting Multiple Cores</title>
		<link>https://blog.xojo.com/2018/01/25/supporting-multiple-cores/</link>
		
		<dc:creator><![CDATA[Norman Palardy]]></dc:creator>
		<pubDate>Thu, 25 Jan 2018 20:13:00 +0000</pubDate>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[Console]]></category>
		<category><![CDATA[CPU]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Threads]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=3832</guid>

					<description><![CDATA[With today's multi-core CPU's it seems that an application made with Xojo running on a single core is somewhat restricting. If you have a lot of data to process, large images to manipulate or other things that could happen in the background, it would seem that with a multi-core machine you could do this faster "if only Xojo would make threads preemptive". If you think you need preemptive threads today, try the helper application approach and I think you'll be pleasantly surprised at how well it works.]]></description>
										<content:encoded><![CDATA[<p>With today&#8217;s multi-core CPU&#8217;s it seems that an application made with Xojo running on a single core is somewhat restricting. If you have a lot of data to process, large images to manipulate or other things that could happen in the background, it would seem that with a multi-core machine you could do this faster &#8220;if only Xojo would make threads preemptive&#8221;. We get a lot of requests for preemptive threads so that people can take advantage of multiple cores.</p>
<p><span id="more-3832"></span></p>
<p>It&#8217;s been suggested that this should be <em>easy</em> to do. Just make threads preemptive (so that they will then run on any available core) and voila! Unfortunately, it&#8217;s not that simple. Let&#8217;s look at why the current threads are not preemptive. It&#8217;s hard for you, the developer, to work with preemptive threads. Some languages, like Java, have language features built in to them to try and help make this less work, but it is still hard to get right and very hard to debug when you don&#8217;t. Much of the framework would need updating to be thread safe and your application&#8217;s user interface is not thread safe on any platform because the operating systems themselves don&#8217;t have thread-safe user interface code. If you access something from a pre-emptive thread and that something is not thread-safe, there&#8217;s a very good chance your application is going to crash. We have had to go to a lot of extra work just to make the threads you have today work without causing problems.</p>
<p>The Xojo language already has functions like mutex and semaphores that help you make a multi-threaded program. But you have to protect every place you might set a value that could be shared by many threads. This would mean protecting any globals and pretty much anything that is not local to the method or the thread being executed. That&#8217;s very different than what you have to do today and a lot more work. It&#8217;s just not <em>simple</em> or <em>easy to use</em> the way most of Xojo is designed to be.</p>
<p>The end goal is to use all cores and thereby make your software more responsive, faster, or able to handle more data, or do more things all at the same time. There&#8217;s been a way to do this for as long as Xojo has supported building console applications. The design is to create a main application (GUI or not) and use other helper applications to run separate tasks. The main application and the helpers can communicate in any one of several ways: IPCSockets, TCPSockets, UDPSockets, XML, files, or just about any other way you can dream of. The upside to this way of solving the problem is you can design and implement the main application and the helpers independently and use the debugger to debug each independently. You can use any data in either program in the same way you always have. You don&#8217;t have to worry about the framework being thread safe as the helper and main application run as completely separate processes with their own memory space. Most importantly, you can do this today.</p>
<p>I&#8217;m not going to say it&#8217;s simple. You have to think about what portion of your application can be segmented out into a helper console application. You have to design the communications between the main and helper applications. You have to write, test and debug them. But you don&#8217;t have to worry about variables changing mysteriously because some other thread changed the value. You don&#8217;t have to use lots of mutexs or sempahores to block other threads from altering things when you least expect them. And you can use the entire framework that is available to console applications. Last but not least, you can run as many instances of these helper applications as your computer (or all the computers available to you) can run.</p>
<p>If you think you need preemptive threads today, try the helper application approach and I think you&#8217;ll be pleasantly surprised at how well it works.</p>
<p>For more information: <a href="https://blog.xojo.com/2013/07/26/take-advantage-of-your-multi-core-processor/">Take advantage of your multi-core processor</a></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
