Game Programming in C++ Overview Threads in games Threads in ...

12 downloads 302190 Views 37KB Size Report
Game Programming in C++. Arjan Egges ... “The game is built around me, so I control how threads are ... Windows stays in control of how long each thread gets  ...
Overview

Game Programming in C++ Arjan Egges

• • • • •

Processes vs. Threads Creating threads Locking mechanisms Race conditions & deadlocks Volatile

Lecture #10: Threads & synchronization

Threads in games • Threads are very common in game engines – Render thread – Game/Event loop – Different threads for AI, physics, … – Other update threads

• Challenging task to ensure stability

Processes vs. Threads • What is a process? – An OS entity that provides the context for: • Executing program instructions • Managing resources (memory, I/O handles, and so on)

• A process is protected from other OS processes via memory management • Every process has its own address space

Threads in game engines Why is this a problem? • Not all libraries and engines are threadsafe • Game/graphics engines may have “ego” problems – “The game is built around me, so I control how threads are used!” – GUI libraries vs. Graphics engines

Processes vs. Threads • Each process must have at least one ‘path of execution’ – Main thread

• A thread is a path of execution – Threads share the same OS address space • Cheap data exchange

– Threads can be stopped, started, paused, and new threads can be created – Threads are not ‘protected’ (blocking or aborting a thread could influence the whole program

1

Threads • Multithreading does not automatically increase performance (in fact, quite the opposite!): – Multiple threads accessing the same data can result in a lot of synchronization overhead

• Starting a thread – Eager spawning – On-demand spawning

Creating a Win32 thread #include // Win32 threads #include #include using namespace std; DWORD WINAPI MyThread(LPVOID n) { std::string name = string(n); for (int i=0;i