Low-Level Programming: Post 17 25/02/2016
February 25th 2016 is the date of the seventeenth lesson on Low-Level Programming.
Before the start of the lesson, in that we were shown some slides on the topics at hand, we were reminded of the overview of the course, in that, we were shown how our overall study in the course should be. In short, the reason we were shown this was an indication that some of us in the course needed to work and attend more.
After that, we were shown the main points that we were going to cover in the next couple of hours...
Before the start of the lesson, in that we were shown some slides on the topics at hand, we were reminded of the overview of the course, in that, we were shown how our overall study in the course should be. In short, the reason we were shown this was an indication that some of us in the course needed to work and attend more.
After that, we were shown the main points that we were going to cover in the next couple of hours...
- Threading: Job Scheduling.
- Mutexes: What are they and how do they work?
- Atomics: Atomic instructions.
- C++11 Threads/Tasks: Threads VS tasks, pros and cons.
Threading
Threading
- What is it?: Threading is the execution of parallel tasks running outside of a single point of execution.
- Why?: Modern day CPU architecture is completely based around the ideal of using multiple CPU cores running unique tasks at the same time.
- Multi-Threaded: Programs that utilise this type of technology are often known as being ‘multi-threaded’. In this modern day of development, you can’t get away from working with threads.
The Problem
- Single Threaded Game Loop: Traditionally, we break the engine into sub tasks, run them in order and rinse and repeat.
- Sequential: This approach was fine before the use of multi-core CPUs, but on a modern day system this would leave all the other x number of cores unused.
Thread Control
- Master Thread: In this scenario, we require a master thread that that controls and synchronises the secondary subsystem threads and handles the game’s high level logic i.e. the game loop.
Pipe-Lining
- Pipeline Parallelism: Running two parts of the same pipeline in synchronised threads. This is known as lockstepping. i.e. we need the first part to finish before the second starts.
- Graphics: The graphics rendering can be started on a different thread, as long as the update of game logic has been completed.
Task-Schedulers
- Desire: Task scheduling was designed to meet the desire for more fine-grained levels or parallelism (similar to fork and join).
- Tasks: The tasks themselves i.e. logic, physics etc. can be broken down in to smaller tasks. If safe to do so, these subtasks can be run in parallel.
- Scheduler: The task scheduler approach is a system that allows us to ‘throw’ these smaller subtasks on to threads and process them in parallel.
Sub-System Threads
- Dedicated?: Each worker thread is a kind-of dedicated thread. Instead of one subsystem it handles tasks. It works through them.
- Concurrent Queue: Just like our lockstepping example, the we can use a concurrent queue, add jobs to it and the worker threads process them.
- Agnostic: The worker threads are agnostic. We don’t care which thread handles which jobs, just so long as the queue is processed.
- Event Thread: There is one event for each worker thread. Those threads then listen to their designated events and start working when the signal is triggered.
Task Groups
- Grouping: A more advanced version of this system involves creating a task group for each system.
- Threads: Multiple threads work on the same task group. Obviously they would need to manage the queue amongst themselves.
Dependencies
- Task Groups: It may not be safe or sensible for threads to process tasks groups as and when. Task groups allow us to setup dependencies.
- Threads: The thread that finishes the last item in the task group schedules the next one.
Improvements
- Centralised: Centralised or per-thread specific task lists.
- Priorities/Affinities: Allow some tasks to have higher priorities and certain tasks or groups to be assigned to a designated hardware thread.
- Batching: Batch up a series of similar tasks (fork and join) and dispatch using the thread scheduler system. You could also pin specific job threads to cores as well.
Mutexes
Mutex
- What is it?: A mutex is a program object that allows multiple threads to access the same resource.
- Shared Data: It’s designed as a synchronisation primitive with the intention of protecting shared data that’s accessed concurrently.
- Exclusive: A mutex offers exclusive, non-recursive ownership semantics.
- A calling thread owns a mutex from the time it successfully calls lock through to unlock.
- All other threads trying to access a locked mutex will fail.
- A calling thread must not own the mutex prior to calling lock or try_lock.
Mutex Requirement
- When: A mutex quite simply is required when shared data is under concurrent read and writes i.e. when one thread may read and another write at the same time.
- Safety: The mutex ensures that we don’t access the shared data unless no other thread currently accesses it. If the mutex is currently locked, the thread will need to wait.
- Semaphore: A mutex is a type of semaphore. An object designed for concurrent usage. Generally suitable when a shared object isn't under a huge amount of contention.
Atomics
Atomics
- Contention: When a concurrent object is under high contention, than implementing the use of atomics over things like mutex’s is a good design decision.
- Atomic Stores: On some platforms store and loading values are already atomic i.e. their operations only generate a single instruction.
- Platform: Each platform has its own ways of exposing atomic operations. Before C++11 game engines would need to create an abstraction to allow ease of use.
- Operations: An atomic operation is an operation or set of operations that appears for all intents and purposes to occur instantaneously.
- Options: To ensure ordering you can utilise fencing. There are two types, lightweight and full fences.
- Lightweight: Orders load from memory & Orders store from memory.
- Full Fence: Lightweight plus Commits stores before next load.
- What are they?: A memory barrier, also known as a member, memory fence or fence instruction, is a type of barrier instruction that causes a central processing unit (CPU) or compiler to enforce an ordering constraint on memory operations issued before and after the barrier instruction.
- Necessity: Memory barriers are necessary because most modern CPUs employ performance optimizations that can result in out-of-order execution.
- Re-Ordering Issues: This reordering of memory operations (loads and stores) normally goes unnoticed within a single thread of execution, but can cause unpredictable behaviour in concurrent usage.
- Portable: As mentioned previously; C++11 now provides developers with an atomic library that operates at the platform layer allowing portable code.
- Concurrent objects: Objects under heavy contention should make use of the C++11 atomic library.
- Forbids data races: C++11 atomics forbids data races, when the same object is being written to concurrently.
- Guidance: The rule; If multiple threads access the same variable concurrently, and at least one thread modifies it, all threads must use C++11 atomic operations.
C++ Atomics API
- Sequentially Consistent:
- Similar to Java volatiles.
- Used in books / literature.
- Slower with modern architectures.
- Low-Level Atomics:
- Similar to C/C++ volatiles.
- Much like the game atomics.
- Translate more closely to native instructions.
C++11 Threads
C++11 Threads
- How to create one: std::thread is the libraries version of a thread. You can use it to construct a new thread. The constructor can be passed the function to run as a function pointer.
- Join: If you want to wait for the thread to finish executing, you can call join on it.
- ID: How do we distinguish between threads, well they have IDs. The std::thread class has a get_id() function. The ID is obviously unique.
C++11 Tasks
- How to create one: C++11, allows us to create threaded tasks and store the result of the thread’s execution in a std::future.
- Futures: You can retrieve the exit value of a thread, or even wait on a thread’s execution via it’s future handle.
Prefer Tasks over Threads
- Return Value: Tasks allow us easy access to a thread’s return value via the future object it creates. This is far from straightforward with a std::thread.
- Exceptions: Exceptions in threads cause all threads to terminate. With tasks we can actually interrogate any exceptions that are thrown and the program does not terminate.
- Thread Management: Using std::threads mean you need to manage the number of threads and oversubscription numbers. Too many threads will slow the system down via context switching. With async tasks it does not guarantee the launch of a new thread, thus protection against oversubscription. It can even schedule the thread to run later.
After the couple of hour long slides, we than proceeded to the practical task for this week. In this week, we had to add various components to the DungeonDeath game. Unfortunately, this was a bit of a struggle, since we had to add the LibCaca files into the downloaded folder via Gitlab. However, despite this and with a little bit of help from the tutor, I completed the first task given to us. I couldn't complete any more, however, as I ran out of time to attempt the other tasks.


