use 'with' keyword

Replaced acquiring and releasing thread locks with the 'with' keyword.