Added locking implementation. No deadlock detection yet.
Added correct locking implementation