Junior — Middle
Explain what a single thread of execution in a program is and how it works.
sobes.tech AI
Answer from AI
A thread is a sequence of commands that the processor executes sequentially. In the context of a program, one thread is one path of code execution.
When a program starts, it has a main thread that executes instructions in order. If multiple tasks need to be performed simultaneously (in parallel), additional threads are created.
Each thread has its own call stack and can execute code independently, but all threads share the same process memory.
Example of creating and starting a thread in C#:
using System;
using System.Threading;
class Program {
static void Main() {
Thread thread = new Thread(() => {
Console.WriteLine("Execution in a separate thread");
});
thread.Start();
Console.WriteLine("Execution in the main thread");
}
}
Thus, a thread is a basic unit of execution that allows a program to do multiple things simultaneously.