Skip to main content

What is Concurrent Programming? (With Code Example)

· 2 min read
PSVNL SAI KUMAR
SDE @ Intralinks

What is Concurrent Programming?

Concurrent programming refers to a programming paradigm where multiple tasks or processes are executed at the same time. This does not necessarily mean that they run simultaneously (as in parallel computing), but rather that they make progress independently, potentially switching between tasks to maximize efficiency.

Concurrent Programming

Key Features of Concurrent Programming

  1. Task Independence: Multiple tasks can start, execute, and complete in overlapping time periods.
  2. Resource Sharing: Tasks share resources like memory or CPU time, but they are designed to avoid conflicts through techniques like synchronization.
  3. Improved System Utilization: Concurrent programs make better use of system resources by avoiding idle waiting, especially in I/O-bound applications.

Real-World Example of Concurrent Programming

Let’s consider a real-world scenario where a web server handles multiple user requests. Using concurrent programming, the server doesn't need to wait for one request to finish before starting the next one. Instead, it processes them concurrently, improving overall responsiveness.

Python Example: Downloading Multiple Web Pages Concurrently

import time
import concurrent.futures
import requests

# A function to download a web page
def download_page(url):
print(f"Starting download: {url}")
response = requests.get(url)
time.sleep(1) # Simulating some processing time
print(f"Finished downloading {url}")
return response.content

urls = [
'https://www.example.com',
'https://www.example.org',
'https://www.example.net'
]

# Using concurrent programming to download all pages at once
start_time = time.time()

with concurrent.futures.ThreadPoolExecutor() as executor:
results = executor.map(download_page, urls)

end_time = time.time()
print(f"Downloaded all pages in {end_time - start_time} seconds")

Importance of Concurrent Programming

Concurrent programming is essential in systems where responsiveness and resource efficiency are critical, such as:

  • Web servers handling multiple requests.
  • Mobile apps performing background tasks.
  • Operating systems managing multiple processes.

Concurrent vs. Parallel Programming

While both aim to execute multiple tasks, concurrent programming focuses on managing multiple tasks at once, while parallel programming involves running multiple tasks at the exact same time, often on multiple processors.

Understanding concurrency helps developers design efficient and responsive software in today's multi-core and distributed environments.