
206
이펙티브 러스트
드
3
는
C
다음
A
를 잠근 상태일 수 있다.
이 문제를 해결하는 가장 간단한 방법은 잠금에 대한 스코프를 좁혀서 두 가지 잠금이 동시에
발생하지 않게 하는 것이다.
/// 새로운 플레이어를 추가하고 현재 게임에 참여시킨다.
fn add_and_join(&self, username: &str, info: Player) -> Option<GameId> {
// 새 플레이어를 추가한다.
{
let mut players = self.players.lock().unwrap();
players.insert(username.to_owned(), info);
}
// 새 플레이어를 참여시킬 공간이 있는 게임을 찾아서 참여시킨다.
{
let mut games = self.games.lock().unwrap();
for (id, game) in games.iter_mut() {
if game.add_player(username) {
return Some(id.clone());
}
}
}
None
}
/// ID가 `username`인 플레이어를 금지시키고, 현재 참여 중인 게임에서 제거한다.
fn ban_player(&self, username: &str) {
// 해당 사용자가 참여한 게임을 모두 찾아서 빼낸다.
{
let ...