PHP 8.1 introduced the new Fiber class (see the proposed RFC here https://wiki.php.net/rfc/fiber), which allows running coroutines inside your script, i.e. two functions executing simultaneously
This article describes a TDD (Test Driven Development) approach to implement a Finite State Machine (FSM) using PHP+Laravel. However, such method is general and could be used in the programming language of your choice.