Add thread synchronization and some tiny changes