You can have a global function that captures a mutex object and a global function that returns a mutex object.
The thread that the database is supposed to use is trying to call a function that captures the mutex. If the mutex is already in use, the function returns 0. If the mutex is available, the grab mutex function marks the mutex as unavailable and returns 1 for success.
Any subsequent calls to capture the mutex will fail until the thread that successfully captured the mutex calls the mutex return function.
Any thread that tries and cannot capture the mutex can be looped until the mutex is successfully captured (i.e. the thread will wait for the mutex). You can also enter a timeout here.
A mutex object can be as simple as a bool, or you can use other more complex mutexes (windows.h has mutex objects).
If you create your own mutex, VITALLY is important for it to be unstable.
No thread can access the database if it does not have a mutex.
source share