working version with thread management inside the device