with _semaphores_lock: #part1
if name not in _semaphores: # part1 _semaphores[name] = semaphore.Semaphore() # part1
sem = _semaphores[name] # part3
....
with _semaphores_lock: # part2
if not sem.balance < 1:# part2 del _semaphores[name]# part2
The solution you propose does not work in the following scenario:
one thread (T1) does part1
an other one does part2
T1 use a lock no more in _semaphores
with _semaphores_lock: #part1
_ semaphores[ name] = semaphore. Semaphore( ) # part1
del _semaphores[name]# part2
if name not in _semaphores: # part1
sem = _semaphores[name] # part3
....
with _semaphores_lock: # part2
if not sem.balance < 1:# part2
The solution you propose does not work in the following scenario:
one thread (T1) does part1
an other one does part2
T1 use a lock no more in _semaphores