Exploring concurrent programming.
Sample codes demo concurrency via async, multithreading and multiprocessing methods in:
py: Pythoncs: C# / .NETcpp: C++
py/sample_thread.py allows testing multithreading and multiprocessing for different tasks, including I/O-bound and CPU-bound.
The following tests demonstrates that for CPU-bound tasks in Python, multithreading doesn't help, while multiprocessing helps.
- CPU-Bound, Sequential: ~15s (benchmark)
- CPU-Bound, Multithreading: ~15s (no gain)
- CPU-Bound, Multiprocessing: ~5s (huge gain)
py/sample_async.py leverages Python's asyncio.
/cs/ConsoleApp provides a menu of different concurrency methods. Tasks print their unique IDs (0 - 9), also color coded for two concurrent tasks. The main method prints a heartbeat character (♥), allowing to recocognize the methods that don't block the main thread:
- Independent I/O-bound tasks
- Independent CPU-bound tasks
- I/O-bound operations over a collection
- CPU-bound operations over a collection
/cpp/main.cpp demos concurrency in C++, with the following options. The task IDs, colors, and heartbeat (♥) are similar to the C# demo.
- Synchronous
- Multithreading via
std::async
- Multithreading via
std::thread
thread_safe.cpp demos and benchmarks two common thread-safe methods in C++:
-
With lock: Using
mutexwhich, at the expense of higher overhead, ensures that only one thread can access a section of the code at a time. -
Lock-free: Using
atomicwhich is generally faster, at the expense of higher complexity and being applicable to a limited set of data types. Its magic is related to hardware-level CPU instructions.
Also, the lock-free version includes cache alignment that avoids "False Sharing", which is a performance-degrading issue if independent variables reside on the same CPU cache line.
The benchmarking result favors the lock-free method in this particular test, as expected:











