| name | multithreading |
| description | Multithreading and concurrency patterns for game servers including synchronization primitives |
| sasmp_version | 1.3.0 |
| version | 2.0.0 |
| bonded_agent | 01-game-server-architect |
| bond_type | SECONDARY_BOND |
| parameters | {"required":["threading_model"],"optional":["thread_count","queue_size"],"validation":{"threading_model":{"type":"string","enum":["single","thread_per_connection","thread_pool","actor"]},"thread_count":{"type":"integer","min":1,"max":256,"default":0},"queue_size":{"type":"integer","min":100,"max":100000,"default":10000}}} |
| retry_config | {"max_attempts":1,"fallback":"single_threaded"} |
| observability | {"logging":{"level":"debug","fields":["thread_id","task_type","duration_us"]},"metrics":[{"name":"thread_pool_active_threads","type":"gauge"},{"name":"task_queue_size","type":"gauge"},{"name":"task_execution_duration_us","type":"histogram"},{"name":"lock_contention_count","type":"counter"}]} |
Multithreading for Game Servers
Implement thread-safe game server architectures with proper synchronization.
Threading Models
| Model | Pros | Cons | Use Case |
|---|
| Single-threaded | Simple, predictable | Limited scale | Casual games |
| Thread-per-connection | Simple | High overhead | Small servers |
| Thread pool | Efficient | Complex | Most games |
| Actor model | No locks | Learning curve | Distributed |
Synchronization Primitives
Mutex (Mutual Exclusion)
std::mutex game_state_mutex;
void updatePlayerPosition(int playerId, Vector3 pos) {
std::lock_guard<std::mutex> lock(game_state_mutex);
players[playerId].position = pos;
}
Read-Write Lock
std::shared_mutex players_rwlock;
Vector3 getPlayerPosition(int playerId) {
std::shared_lock<std::shared_mutex> lock(players_rwlock);
return players[playerId].position;
}
void setPlayerPosition(int playerId, Vector3 pos) {
std::unique_lock<std::shared_mutex> lock(players_rwlock);
players[playerId].position = pos;
}
Spinlock (Low Latency)
std::atomic_flag spinlock = ATOMIC_FLAG_INIT;
{
(spinlock.(std::memory_order_acquire)) {
}
spinlock.(std::memory_order_release);
}