Improve thread_mutex error handling and delete old file