Concurrency in OOP

Understanding Concurrent Programming in C++

What is Concurrency?

Concurrency is the ability of a program to execute multiple tasks simultaneously. In C++, concurrency is achieved through threads, async operations, and parallel algorithms. It allows programs to perform multiple operations at the same time, improving performance and responsiveness.

Concurrency क्या है? (हिंदी में)

Concurrency एक program की ability है multiple tasks को simultaneously execute करने की। C++ में, concurrency threads, async operations, और parallel algorithms के through achieve की जाती है। यह programs को multiple operations को same time पर perform करने की allow करता है, जिससे performance और responsiveness improve होती है।

Key Points:

  • Parallel Execution: Multiple tasks running simultaneously
  • Resource Sharing: Safe access to shared resources
  • Synchronization: Coordinating concurrent operations
  • Performance: Improved throughput and responsiveness

Types of Concurrency

Threads

std::thread, std::jthread

Async Operations

std::async, std::future

Parallel Algorithms

std::execution::par

Concurrency Rules

Rule Description
Thread Safety Protect shared resources
Deadlock Prevention Avoid circular dependencies
Race Condition Prevent data races
Resource Management Proper cleanup of resources

Simple Example

#include <iostream>
#include <thread>
#include <mutex>
#include <future>
#include <vector>
#include <algorithm>

// Thread-safe counter using mutex
class Counter {
private:
    std::mutex mutex;
    int value = 0;
    
public:
    void increment() {
        std::lock_guard<std::mutex> lock(mutex);
        ++value;
    }
    
    int get() {
        std::lock_guard<std::mutex> lock(mutex);
        return value;
    }
};

// Async function
int asyncOperation(int x) {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    return x * x;
}

// Function demonstrating concurrency
void concurrencyExample() {
    std::cout << "\nConcurrency Example:" << std::endl;
    
    // Thread example
    Counter counter;
    std::vector<std::thread> threads;
    
    for (int i = 0; i < 5; ++i) {
        threads.emplace_back([&counter]() {
            for (int j = 0; j < 1000; ++j) {
                counter.increment();
            }
        });
    }
    
    for (auto& thread : threads) {
        thread.join();
    }
    
    std::cout << "Counter value: " << counter.get() << std::endl;
    
    // Async example
    std::vector<std::future<int>> futures;
    
    for (int i = 1; i <= 5; ++i) {
        futures.push_back(std::async(std::launch::async, asyncOperation, i));
    }
    
    for (auto& future : futures) {
        std::cout << "Async result: " << future.get() << std::endl;
    }
    
    // Parallel algorithm example
    std::vector<int> numbers(1000);
    std::iota(numbers.begin(), numbers.end(), 1);
    
    int sum = 0;
    std::mutex sumMutex;
    
    std::for_each(std::execution::par, numbers.begin(), numbers.end(),
        [&sum, &sumMutex](int n) {
            std::lock_guard<std::mutex> lock(sumMutex);
            sum += n;
        });
    
    std::cout << "Parallel sum: " << sum << std::endl;
}

int main() {
    concurrencyExample();
    return 0;
}

उदाहरण की व्याख्या (Example Explanation)

इस उदाहरण में concurrency के different aspects को demonstrate किया गया है:

  • Thread Safety: Mutex का use करके shared resources को protect करना
  • Async Operations: std::async का use करके parallel tasks को execute करना
  • Parallel Algorithms: std::execution::par का use करके algorithms को parallel execute करना
  • Resource Management: RAII principles का use करके resources को manage करना
  • Thread Synchronization: Threads को coordinate करना
  • Performance Optimization: Parallel execution से performance को improve करना

Benefits of Concurrency

Concurrency के फायदे

  1. Performance
    • Better resource utilization
    • Improved throughput
  2. Responsiveness
    • Non-blocking operations
    • Better user experience
  3. Scalability
    • Multi-core utilization
    • Distributed processing

Best Practices

  • Use RAII for resource management
  • Prefer high-level abstractions
  • Avoid raw threads when possible
  • Use thread-safe containers
  • Minimize shared state