From the course: Threading in C#

Understanding threading - C# Tutorial

From the course: Threading in C#

Start my 1-month free trial

Understanding threading

- [Instructor] A thread is a basic unit of execution that gets allocated processor time by an operating system. It's a sequence of program instructions that can be managed independently by a scheduler. And a scheduler or a thread scheduler is part of the operating system. If you ever work on a Windows application, like Microsoft Word or Excel, you know what an application is. It consists of one or more processors. So, in the simplest terms a process is an executing program for an application. If you were to right click on your taskbar and click on task manager, and then more details, you can see the processes here. As you can see, we have Google Chrome running, Microsoft PowerPoint, and Microsoft Visual Studio. They're all independent processes. Every single process can have one or more threads running in the context on the process. In a single-threaded program, only one thread has full access to the process. And in a multithreaded program, we have an execution model that allows multiple threads to coexist within the process. Threading is also called multithreading. These threads execute independently, but are able to share resources within the context of the process. So, what are the most common scenarios for multithreading? In a thick client application, like a Windows app or an IOS app, it's always a good idea to run computation-intensive code on a different thread than the UI thread. The reason is simple, we want the UI thread to be fully responsive and we want to offload the computation-intensive code in a completely different thread. When it comes to divide and conquer algorithms, for example, map reduced algorithm, we can use multithreading. This way, we can take advantage of multiprocessor computers. And if you are familiar with web servers, millions and billions of requests can come in simultaneously. So, multithreading is the only way to ensure scalability. Here's a simple diagram that shows a main thread that's running. And while the main thread is running, you can have multiple worker threads that get spawned off. These worker threads can continue to do completely different tasks than the other threads. And once they're finished with the tasks, they will stop execution and then once we have all the threads not running anymore, the application will end.

Contents