There are many different ways to solve your problem based on your specific implementation. A few basic ideas might be:
Define a boolean value that indicates whether the player is working (true = running, false = not)
Before each call related to the player, check this variable and, if it is false (the player is stopped), close the function (return immediately)
Then you call removeTimer and you set the variable to false to close the player.
However, since addTimer is a function that creates threads, race conditions can sometimes exist (what you called the "middle of execution"). This is one of the main problems when using threads.
You need to find and fix them using tools such as mutexes, semaphores, ... The choice of these tools largely depends on the strategy that you want to implement in order to avoid these race conditions.
So there is no general solution . If performance is not a concern, you can use this simple one-lock solution. This is the basic implementation of the critical section strategy. This prevents the launch of some fragments of code (closing the player and making critical sound calls).
#include <pthread.h>
Of course, I cannot explain all race avoidance strategies in a simple stackoverflow article. If you need to improve performance, you must determine exactly what your concurrency issue is for your code and choose the right strategy.
source share