Practical Thread Programming
Thread Synchronization Mechanisms
Mutex (Mutual Exclusion)
#include <mutex>
#include <thread>
std::mutex shared_mutex;
void critical_section(int thread_id) {
shared_mutex.lock();
// Protected critical section
std::cout << "Thread " << thread_id << " accessing shared resource" << std::endl;
shared_mutex.unlock();
}
Synchronization Techniques
flowchart TD
A[Thread Synchronization] --> B[Mutex]
A --> C[Condition Variables]
A --> D[Atomic Operations]
A --> E[Semaphores]
Thread Pool Implementation
#include <thread>
#include <vector>
#include <queue>
#include <functional>
class ThreadPool {
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
bool stop;
public:
ThreadPool(size_t threads) : stop(false) {
for(size_t i = 0; i < threads; ++i)
workers.emplace_back([this] {
while(true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
if(this->stop && this->tasks.empty())
break;
if(!this->tasks.empty()) {
task = std::move(this->tasks.front());
this->tasks.pop();
}
}
if(task)
task();
}
});
}
};
Concurrency Patterns
Pattern |
Description |
Use Case |
Producer-Consumer |
Threads exchange data |
Buffered I/O operations |
Reader-Writer |
Multiple read, exclusive write |
Database access |
Barrier Synchronization |
Threads wait at specific point |
Parallel computation |
Advanced Thread Techniques
Condition Variables
#include <condition_variable>
std::mutex m;
std::condition_variable cv;
bool ready = false;
void worker_thread() {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, []{ return ready; });
// Process data
}
void main_thread() {
{
std::lock_guard<std::mutex> lock(m);
ready = true;
}
cv.notify_one();
}
Thread Safety Strategies
- Minimize shared state
- Use immutable data
- Implement proper locking
- Avoid nested locks
flowchart TD
A[Thread Performance] --> B[Minimize Context Switching]
A --> C[Optimize Thread Count]
A --> D[Use Lock-Free Algorithms]
A --> E[Reduce Synchronization Overhead]
Error Handling in Multithreading
#include <stdexcept>
void thread_function() {
try {
// Thread logic
if (error_condition) {
throw std::runtime_error("Thread error");
}
} catch (const std::exception& e) {
// Handle thread-specific exceptions
std::cerr << "Thread error: " << e.what() << std::endl;
}
}
LabEx Multithreading Best Practices
- Use standard library threading support
- Prefer high-level abstractions
- Test thoroughly
- Monitor resource usage
Common Multithreading Pitfalls
Pitfall |
Solution |
Race Conditions |
Use mutexes, atomic operations |
Deadlocks |
Implement lock ordering |
Resource Contention |
Minimize critical sections |