Use condition variable to improve efficiency.

Also: patch mem leak.
Cleanup. Remove unnessiasry unlock/relock.