Added mutexes and semaphores on posix/windows.
Fixed resource leaks.