adding exit function and fixing onterminate synchronization issues