Multi-threaded Mandelbulbs

Visions Of Chaos now supports multithreaded rendering for Mandelbulbs, Mandelbox and Kaleidoscopic IFS rendering. 2x speedup for dual core CPUs. 8x speedup for the new i7 8 core CPUs.

I had never done multiple threaded code in Delphi before and found it difficult to get the right info from googling tips/hints etc. So here are a few tips of my own for someone trying to write multi-threaded code in Delphi.

1. When converting a non threaded bit of code into threaded, make sure the thread has all needed variables within the thread itself. Minimize accessing global variables as much as possible.

2. When you do need to access (read or write) a global variable or the main form or any dialog, forget using Synchronize. I found it tedious to implement and slower than using critical sections. To use critical sections;

Create a global variable
var criticalsection:TRTLCriticalSection;

Before you start/spawn the threads, define the critical section
InitializeCriticalSection(CriticalSection);

Now, during any part of the threaded code that needs to access a global variable or the main form, surround the code as follows
EnterCriticalSection(CriticalSection);

LeaveCriticalSection(CriticalSection);

After all threads have finished, remove the critical section
DeleteCriticalSection(CriticalSection);

Using critical sections is much easier than setting up separate procedures within your thread that are called with synchronize, and I found the performance and speed was faster with critical sections.

3. If you set the priority of created threads, make sure the priority is the same or lower than the main application priority. If this is not done then the main form will be less responsive and/or the threads will not be as responsive when running.

Hopefully that helps someone else getting to grips with threads in Delphi. Once you get the basics down threads are not that complicated.

Jason.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s