Single-use file lock. It should NOT be used on the file meant to be protected, but a second file exclusively meant to indicate whether some other file or resource is currently locked. This class deletes the lockfile after use as well, meaning if you use it on a file you want to use normally, it will be deleted.
This won't actually prevent access to the relevant resources, but this strategy allows for programs to respect each other.
This class only does locking; any type of error handling has to be done by the programmer using this class.
There's two ways to lock a file; either, the constructor can be used, or a helper method within the class can be used. The helper method exists to make a minor framework around a repetitive check with some function callback; see its documentation for the exact callback details. The callback determines whether or not to continue, as well as allowing the programmer to specify a wait handler. Examples include updating a popup, printing a timer in the terminal, printing or rendering a progress bar, etc.
| static std::shared_ptr< FileLock > stc::FileLock::dynamicAcquireLock |
( |
const std::filesystem::path & |
path, |
|
|
std::function< bool()> |
control, |
|
|
unsigned int |
sleepSeconds = 1 |
|
) |
| |
|
inlinestatic |
Utility method for lock acquiring; instead of an immediate fast fail or blocking while waiting for an unlock, this method uses failure to call a control method that allows for more responsive user interfaces.
The control method can also completely abort the locking. For instance, if you only have so much time to spend on waiting for the lock, your control function can check whether some amount of time has passed before returning false.
If there's a UI-centric application, a variable can be used to connect a "cancel" button to the control function, aborting the process if the user has had enough.
Automated systems can attempt to use a timer to determine whether to blatantly ignore the lock or not as well. For instance, if it's guaranteed that certain lock applications won't exceed a certain amount of time locked.
- Parameters
-
| path | The path to the lockfile |
| control | The control function; decides whether or not to continue, and it's highly recommended it's used to update the user interface. |
| sleepSeconds | How long to sleep between attempts; the default is one second. Note that due to fundamental inaccuracies in computers, any time inserted here isn't guaranteed to be accurate down to the max double resolution. Control invokations are not good for an exact indication of elapsed time. |
- Returns
- nullptr if the lock wasn't acquired after control returns false, or if an OPEN_ERROR is met.
-
lock if the lock was acquired