Fixed threading issues.

- Added a mutex to avoid race conditions.
- Moved a function for releasing resources into the rendering event
  (it should be done in the GL thread).