Tuesday, November 26, 2013

Multi-Threading



Multi-Threading
Multi-Threading might sound like some sort of super complicated tech term. No fear, at the ending for this blog you should know the basics of it. First off, a thread in the land of computers is the smallest sequence of programmed instructions that can be managed independently by an operating system scheduler. We will talk about the system scheduler later on. Most of the programs I have coded only run on one thread but my laptop has 4 threads. Those other 3 threads are basically just sitting on the couch not doing anything for my program. As a result my program is running below optimal performance because those other cores could speed it up. To fully utilize my computers performance I can multi-thread my program so that it uses all four threads. Doing so is actually hard and we will talk about that later on.

An operating Scheduler is implemented by an operation system. The Scheduler schedules the time a thread has to process and the order that the threads will be processed. There are plenty of implementations of a scheduler which include but are not limited to: first in first out which acts like a queue where the first thread registered is the first one processed, and Round-robin, where the scheduler assigns a fixed time unite per process, and cycles through them.

The difference between code structure between single and Multi-Thread can be very large. One problem is that Multi-Threaded code needs to be syncretised unlike single threaded. One Advantage of Multi-Threading is that while a CPU is idling it can be used to run another thread. When coding for a multi-threaded program, the code needs to be as independent as possible so that they can be run on a thread. For example physics can be run on one thread and rendering on another. This example will need to sync up the physics and rendering when drawing to the screen because the physics needs to give data to the rendering logic. To sync the two threads one thread has to be locked so that it stops processing data. If the thread is not locked the data that is being read by the rendering might at the same instance be written to by the physics. The outcome cannot be well defined but regardless the values read will be garbage. For every Lock on a thread there needs to be an unlock so that the thread can continue being used.

Multi-Threading gives a developer the ability to use an idling thread and make it process another thread of their program. In addition if a thread gets a lot of cache misses other threads can take advantage of the unused resources.  If several threads process the same data they can begin to share their cache. Overall, Multi-Threading increases performance and fully utilizes the computing power that a computer has to offer.

No comments:

Post a Comment