Elaborate the locking mechanism

- Split the locking into functions
- Do the runtime check outside the loop