Implemented main loops with locks to ensure thread-safe operations