Do not release context until the thread has finished executing the main loop

Change-Id: I0ba7c19b9965fce4a91b6ca6f8ff7de8d5aa3d61