Understanding Concurrency
Concurrency
The ability to execute multiple tasks simultaneously.
In computer science, concurrency often involves breaking down a problem into smaller, independent tasks that can be executed at the same time, either by multiple processors or through time-sharing on a single processor.
Common Mistake- Concurrency is not the same as parallelism.
- While concurrency involves managing multiple tasks at once, parallelism specifically refers to executing multiple tasks simultaneously on different processors.
Advantages of Concurrency
Improved performance: By dividing tasks and processing them simultaneously and independently, this approach can significantly reduce the time required to complete a program.
ExampleIn a web server, handling multiple client requests concurrently ensures faster response times and better user experience.
Resource utilisation: Concurrent processing maximises CPU utilisation by ensuring that processors are not idle.
ExampleWhile one task waits for I/O operations to complete, another task can use the CPU for computation.
Scalability: Concurrent processing allows systems to scale by adding more processors or cores, accommodating increased demand.
ExampleCloud computing platforms use concurrency to distribute workloads across multiple servers.
Responsiveness: In interactive applications, concurrent processing ensures that the user interface remains responsive while background tasks execute.
ExampleA video editing application can render previews concurrently while the user continues to edit.
Disadvantages of Concurrency
Complexity: Designing and implementing concurrent systems is more complex than sequential systems.
ExampleManaging synchronisation and communication between threads requires careful planning.
Data consistency: Concurrent access to shared data can lead to race conditions, where the outcome depends on the order of execution.
ExampleTwo threads updating a shared counter without proper synchronisation may result in incorrect values.
Deadlocks and starvation
- Deadlocks: Occur when two or more tasks wait indefinitely for resources held by each other.
- Starvation: Occurs when a task is perpetually denied access to resources.