Fix memory leaks due to wrong use of the threads
I will read more carefully pthread documentation next time