Use context manager for `threading.Lock`

It cleans up the code significantly in a couple places, and insignificantly in a lot of places.